If at first you don't succeed, call it version 1.0

Contact Me

Sarvesh Kushwaha
Email : sarveshkushwaha@outlook.com

Total Pageviews

Powered by Blogger.

Friday, 27 January 2017

What are Delegates ? When and why we should use Delegates in C# with example ? #AspNetInterviewQuestionsSeries


Delegates :

Delegate word in English defines that entrust (a task or responsibility) to another person.Same concept is follows in C# with some additional properties.

Delegates Overview :
Delegates have the following properties:

  1. Delegates are similar to C++ function pointers, but are type safe. 
  2. Delegates allow methods to be passed as parameters
  3. Delegates can be used to define callback methods. 
  4. Delegates can be chained together; for example, multiple methods can be called on a single event. 
  5. Used as anonymous methods (inline code). 




Referenced from MSDN. Now Lets understand each statement by code :




1. Delegates are similar to C++ function pointers, but are type safe.
// below delgates definition ensures that when i call this delgate 
 //it should point to a function which has only one integer and as a function 
    //should not return anything
 public delegate void MyTypeSafeDelegate(int intParam);

So delegates in C# gives the guarantee to refer to the valid method with correct signature and parameters.

2. Delegates allow methods to be passed as parameters. 



 //Point 2. Delegates allow methods to be passed as parameters.
 public delegate double MyFunctionDelegate(double intParam);
 
 //using tradaional delgate way 
 public static double DoSomeComputaion(double x, MyFunctionDelegate f)
 {
     double h = 0.0000001;
     return (f(x - h) + f(x)) ;
 }
 // using func delegate,last parameter of func is always an output from
      //  that function
 public static double DoSomeComputaionUsingFunc(double x, Func f) 
 {
  double h = 0.0000001;
  return (f(x - h) + f(x)) ;
 }
 
        //this is the function which will be passed as parameter 
 public static double MyFunctionMethod(double x)
 {
  // Can add more complicated logic here
  return x + 10;
 }

3. Delegates can be used to define callback methods. 
Lets suppose we have two class and one class has a long running task and i want to notify another class the status of that long running task. In that case we can use callback with the help of delegate.

To achieve this i have created two class i.e Program and ClassA. In ClassA i have a long running task and i want to notify the class Program about it. So Lets see the code now how we will achieve this :


 
 //Point 3. Delegates can be used to define callback methods. 
    // Created a class with a long running task and want to notify the class 
//Program about it.
 public class classA
 {
   public delegate void DelCallback(string message);
  
   public void LongrunningTask(DelCallback callbackmessageToProgramClass)
   {
     for(int i =0;i less than 10;i++)
     {
       callbackmessageToProgramClass(i.ToString());
     }
   }
  
 }

//Point3. In class Program creating a void message to print message from callback
    public static void DelegateCallBackPrintMethod(string message)
        {
            System.Console.WriteLine(message);
        }


//Point3. call the long running task and get the info in this class
  
  classA  AOObj= new classA(); 
  AOObj.LongrunningTask(DelegateCallBackPrintMethod);
 

4. Delegates can be chained together; for example, multiple methods can be called on a single event. 

Lets suppose i have two methods and i want to call them on a single event in that case we can use delegates too. I have created two methods addvalues and minusvalues and i want to call them in single event. To chain in this way we call them Multicast delegate.

+= means Delegate.Combine();
-=  means Delegate.Remove();

Code:


//point 4 .  Delegates can be chained together; 
 //for example, multiple methods can be called on a single event.
 public  delegate int MultipleDelCall(int y,int z); 
 private int addValues(int y, int z)
    {
        return y + z;
    }
    private int minusValues(int y,int z)
    {
        return y - z;
    }

//now call these methods by delegate, we can call them on dynamic condition as well
//Point 4 . Delegates can be chained together; for example, multiple methods can
// be called on a single event.
  
  Program p = new Program();
  
     MultipleDelCall dd = p.addValues;
  Console.WriteLine(dd(3,4).ToString()); //calls p.addvalues
  
  dd += p.minusValues;//dd += new d(p.n);
  Console.WriteLine(dd(3,4).ToString()); //calls boths p.addvalues and p.minusvalues
  
  dd -= p.addValues;
  Console.WriteLine(dd(3,4).ToString()); // only calls p.minusvalues

5. Used as anonymous methods (inline code).
 we  can think lambda expression as inline delegate method.

Code:
//Point 5.Used as anonymous methods (inline code).
  
IEnumerable pResult = p.People.Where(z => z.LName=="Kushwaha");
  
//you can see delegate can be used inline anonmoyus method
IEnumerable pResultDelegateWay = p.People.Where( delegate (Person X)
                                                  {
                                          return X.LName == "Kushwaha";}     }

//Point 5.Used as anonymous methods (inline code).
 public class Person
 {
  public string FName{get;set;}
  public string LName{get;set;}
 }
 
 List People = new List{
  new Person{ FName = "Sarvesh", LName ="Kushwaha"},
  new Person{ FName = "Love", LName ="Kushwaha"},
 
 };



Hope my this series will help somebody to get a job :) :) . Happy coding :) 

2 comments:

  1. Florida Accident Lawyer I would like to thank you for your nicely written post, its informative and your writing style encouraged me to read it till end. Thanks

    ReplyDelete
  2. Dengan menjadi bandar dalam permainan ini biasanya lebih memiliki peluang menang yang besar dari pemain lainnya. Keuntungan yang diperoleh jika bandar
    asikqq
    dewaqq
    sumoqq
    interqq
    pionpoker
    bandar ceme terpercaya
    hobiqq
    paito warna terlengkap
    bocoran sgp

    ReplyDelete