Saturday, 19 December 2015

Extension Methods


                               Extension Method

Extension methods allow you to add methods to existing types .And the interesting thing is that you can do it without adding this method  or updating the  original type.

To define and call extension methods consider the following points:

  1. Define a static class that contains the extension method
  2. Define the extension method as static method
  3. Add the first parameter with 'this keyword' upon which this extension method has to be operated on.
  4. If the calling class  and the class which contains the extension method then add 'using' directive to specify the namespace which contains the extension method's class.
  5. Now you can call the extension method as it is the instance method of this type.
Example:
string s="My name is Usman";
s.Display(10);     //Display this name ten times 
Now the point is "Is there any Display method in string class ?The answer is no." But with extension method you can do it without updating the string class and even you can call this method with the instance of string class.


1.This is Class which contains the extension methods .Both class and extension method are with static  and as we have to call this method on string so we would use 'this keyword for first parameter .



2.This  is the calling class which calls the extension  method .In this class you declare a string object 'name'. There is no Display method which can be called with the string object.But with the extension method you can do that.




Output:








Thursday, 17 December 2015

Delegate Part 3

Delegate Part 3

 Decoupling

Delegates also promotes decoupling(It is an Object oriented concept ,I will write about that later).
For Example you have written a class of Calculator ,in which you have written the methods of Addition,Subtraction,Multiplication and Division. Another class is using your these methods.You add some more methods in your class ,in order to use these methods you also need to change your class.
Delegates provides solution to this problem .
Lets  go through in a example


This is  a calculator class which takes inputs and perform Addition,Subtraction,Multiplication and Division operations and return result .

  1. namespace Delegates
  2. {
  3.     delegate int Mathoperation(int num1,int num2);     //Delegate declaration
  4.     class Calculator
  5.     {
  6.         public Mathoperation GetOperation(int option)
  7.         {
  8.             Mathoperation mathOperation = null;             //Currently, delegate object has no reference  
  9.             if (option == 1)
  10.             {
  11.                 mathOperation = Add;
  12.             }
  13.             else if (option == 2)
  14.             {
  15.                 mathOperation =Sub;
  16.             }
  17.             else if (option == 3)
  18.             {
  19.                 mathOperation = Div;
  20.             }
  21.             else if(option==4)
  22.             {
  23.                 mathOperation = Mul;


  24.             }
  25.             else
  26.             {
  27.                 Console.WriteLine("You choose the wrong option");
  28.             }


  29.             return mathOperation;
  30.         }
  31. //Mathematical Operations  
  32.       private int Add(int num1, int num2)
  33.         {
  34.             return num1 + num2;
  35.         }
  36.         private int Sub(int num1, int num2)
  37.         {
  38.             return num1-num2;
  39.         }
  40.         private int Div(int num1, int num2)
  41.         {
  42.             return num1 / num2;
  43.         }
  44.         private int Mul(int num1, int num2)
  45.         {
  46.             return num1 * num2;
  47.         }


  48.     }
}


This is class which is using the above class methods.

  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {


  1. This is a class which is using these methods.
  2. Console.WriteLine("Enter the Option");
  3.             Console.WriteLine("1.Addition");
  4.             Console.WriteLine("2.Subtraction");
  5.             Console.WriteLine("3.Division");
  6.            Console.WriteLine("4.Multiplication");
  7.            int option = int.Parse(Console.ReadLine());
  8.            Calculator Cal_obj=new Calculator();
  9.            int result = Cal_obj.GetOperation(option).Invoke(10, 20);
  10.             Console.WriteLine(result);
  11. }
  12. }
Now whatever changes you made in your Calculator class,It would not affect your Program Class which is using the methods of this class.
This is called decoupling .And Object Oriented Method encourages decoupling .





Delegate Part 2

                                 Delegate Part(2)


Contents:
 In this article following content would be covered
  1. Multi Cast Delegate

     1.Multi Cast Delegate
"A delegate that contains multiple methods are Multi Cast Delegate. 

We use multi cast delegate when there is need of invoking multiple events like we want to print a string and at the same time we want to write this string in the file or that purpose we use multi cast delegate.


Note: These events are invoked in which  sequence you called them. For example there are two events print and read .The order in which read and print would be invoked depends upon the order in which you would call them(events).


 Example1:


//Class 1

  1.  class  Name
  2.     {
  3.         public void Print()
  4.         {
  5.             Console.WriteLine("My Name is Usman Arshad");
  6.         }
  7.     }

  8. //Class 2

  9. class Country
  10.     {
  11.         public void Print()
  12.         {
  13.             Console.WriteLine("I am from Pakistan");
  14.         }

  15.     }

  16. //Main Class
  17. namespace
  18. {

  19. public delegate void Multicastdelegate();
  20.  class Program
  21.     {
  22.  Name obj = new Name();
  23.     Country obj1 = new Country();
  24.             Multicastdelegate delegate = new Multicastdelegate(obj.Print);  //Reference of the print method of class Name
  25.             delegate= delegate + new Multicastdelegate(obj1.Print);      //Just use '+'  sign to add more methods
  26.                 obj1.Invoke();
  27.            }
  28. }









OutPut
My Name is Usman Arshad
I am from Pakistan

You can also write the statement no 30 like this
delegate+=new Multicastdelegate(obj1.Print);

Common Error

A common error which mostly beginner do is that when you pass the reference the method to the delegate object just pass the method name ,do not use function syntax .For example
  Multicastdelegate delegate = new Multicastdelegate(obj.Print( ));
This is a syntax error.Because you only need the name of the method not the method itself

In the next article ,I will write about Call-Back Methods.











Delegates Part 1

Delegate(Part 1)


"A delegate is similar to a pointer function in C or C++  that holds reference of a method.It allows to encapsulate reference to a method inside a delegate object .The delegate object can be passed to a code which can call the reference method."
You often read such definitions about delegates ,this is true but incomplete .The real purpose of a Delegate is to communicate .As 'delegate' is a English language word and  the meaning of this word is to represent or communicate between/among communities ,classes etc.
So the delegate are for communication. We use delegate when one class want to communicate with other class. Of course there are several other ways of doing that,but we should adopt the best way to do any thing.

Why we use Delegate?
C# does not allow us passing method reference directly as arguments  to other methods ,rather it provides delegates.

For example you write a Class(of code) .In this Class you have written a method .A second person working in your team or else where needs this method which you have written in your class. You would provide delegate to that person so that he/she can call this method.

Delegates are especially useful in event driven environment such as Graphical User Interface(GUI) in which you want that code execute when user clicks the button.


Note:Delegates are classes that encapsulate set of references to method.

There are two types of delegate

  1. Single Cast Delegate
  2. Multi Cast Delegate 

(See the detail of both in later section)

Single Cast Delegate:A delegate that contains a single method is known as Single Cast delegate. And it is derived from the class Delegate.
Multi Cast Delegate:  A delegate that contains multiple methods are Multi Cast Delegate. 
Both Single Cast Delegate and Multi Cast Delegate belong to Name-space System.

Before using delegates following point must consider:

"The method header (Parameter & return value) of a delegate and the method whose reference will be within a delegate object must have same method header."

Lets proceed to some practical examples

There are following steps involved in using Delegates:
Declaration
Instantiation
Invocation
Example 1: A simple Delegate

using System;

namespace Simple.Delegate
{
    //  Step 1:Declaration
    public delegate void SimpleDelegate();

    class MyClass
    {
        public static void Print()
        {
            Console.WriteLine("Delegate was Printed");
        }

        public static void Main()
        {
            //  Step 2:Instantiation
            SimpleDelegate simpleDelegate = new SimpleDelegate(Print);

            // Step 3: Invocation
            simpleDelegate();
        }
    }
}

In the later section,I will write further examples of Delegates.

Tuesday, 15 December 2015

Introduction to .NET plateform

                           Introduction to .NET Platform(2)        

                                       1. language Interoperability

.NET provides high level of language interoperability.  The programs written in different languages are all compiled into byte code and then these different parts are combined to create a single application. For example in  a software one module of the software is written in C# and other module is written in VB but when they are combined they act as  a single application. This feature of .NET distinguish it from other development environments.

Any language that can be compiled into byte code or IL is called .NET-compliant language.
 (see the detail .NET-compliant language. in later section)

Language interoperability offers many benefits  for example  C#, Visual Basic .NET and Visual C++ .NET developers, for example, can work side-by-side on the same project without having to learn another programming language—all their code compiles into MSIL and links together to form one program. In addition, the .NET Framework can package old and new components to work together. This allows companies to reuse the code.
  Here is a list of some .NET-compliant language.

  1.  APL Oberon
  2. C# Oz
  3. COBOL Pascal
  4. Component Pascal Perl
  5. Curriculum Python
  6. Eiffel RPG
  7. Fortran Scheme
  8. Haskell Smalltalk
  9. Java Standard ML
  10. JScript Visual Basic .NET
  11. Mercury Visual C++ .NET
  12. F#
  13. IRON PYTHON
  14. IRON RUBY
  15. A#
  16. J#
  17. NETCOBOL
  18. P#








This list is expanding with the passage of time.(I will explain about this in VISUAL STUDIO 2015 blog).

Introduction to .Net Platform

                      Introduction  to .Net Platform(1)

Microsoft .Net commonly pronounced as .NET is  a platform for developing managed application.The word "managed" is a key concept.The word "managed" is a key functionality of .Net Platform.

In traditional compilation process ,the compiler produced executable binary form.Which can be run on operating system immediately. However, in  managed .NET ,the compiler does not produce executable binary format file,rather it produced file in assembly format(Read the detail of about that in later section).


Fig(1)

Fig(1) shows traditional compilation.In which the ,we compile the source code and then the compiler produces executable binary format file.


In .NET the source code is converted in to native code or machine code in two phases.
Phase 1:The compiler of any .NET language converts the source code into Microsoft Intermediate langunage (MSIL) commonly known as IL(Intermediate Language) or Byte Code
Phase 2:The CLR(Common Language Run Time Environment)converts this byte code which is a assembly file into machine code. (Read the detail of these two phases in later section).


                                                            Fig(2)
 Fig(2) is a overall diagram of the compilation process in .NET.


".NET supports multiple programming languages i.e C#,C++,VB etc. When you compile a program in .NET environment ,the compiler of corresponding language converts the source code into byte code or IL ,which is a assembly file. Then the CLR(Common Language Runtime) converts this byte code into machine code or native ."

  Why bother having extra step of converting source code into machine code?
 The key reasons are portability between operating systems, interoperability between languages and execution-management features such as memory management and security.
If the .NET Framework exists  for a platform, that platform can run any .NET program. The ability of a program to run without modification across multiple platforms is known as platform independence.Code written once and run every where without modification saves our time and money.
(See the Interoperability  feature of .Net in later section)

      What is CLR?
1. CLR  not just converts MSIL into machine code ,rather it manages memory,security and other features reliving the programmers from these responsibilities. Like in C++,you have to manage memory by your own,this lead to complexity and you need extra capabilities for that.
2.CLR holds information about the storage of data types and objects.(I will explain about data types and objects later for those who are new in programming ).

  In Part 2 ,I will write about Language Inter-portability feature of .NET ,Common language specification and other important features of  .NET.