Tuesday, June 28, 2011

Delegates (C# Programming)

Delegates have the following properties:
  • Delegates are like C++ function pointers but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods do not have to match the delegate signature exactly. For more information, see Using Variance in Delegates (C# and Visual Basic).
  • C# version 2.0 introduced the concept of Anonymous Methods, which allow code blocks to be passed as parameters in place of a separately defined method. C# 3.0 introduced lambda expressions as a more concise way of writing inline code blocks. Both anonymous methods and lambda expressions (in certain contexts) are compiled to delegate types. Together, these features are now known as anonymous functions. For more information about lambda expressions, see Anonymous Functions (C# Programming Guide).

    public delegate int PerformCalculation(int x, int y);
     
    A delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance.
    Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs
  •  
     
    delegate void Delegate1();
    delegate void Delegate2();
    
    static void method(Delegate1 d, Delegate2 e, System.Delegate f)
    {
        // Compile-time error.
        //Console.WriteLine(d == e);
    
        // OK at compile-time. False if the run-time type of f 
        // is not the same as that of d.
        System.Console.WriteLine(d == f);
    }
    

No comments:

Post a Comment

Thank you for Commenting Will reply soon ......

Featured Posts

#Linux Commands Unveiled: #date, #uname, #hostname, #hostid, #arch, #nproc

 #Linux Commands Unveiled: #date, #uname, #hostname, #hostid, #arch, #nproc Linux is an open-source operating system that is loved by millio...