Most Viewed

Most Viewed

Sunday 15 July 2012

Delegates in C#.Net

Delegates in C#.Net

A delegate is a typesafe function pointer

It points to the methods(or functions )  which match to its signature

A delegate is typesafe becoz it will accept the functions with same datatypes as of its own arguments

if the parametres does not match it throws an error

Advantages:

1. It can point any method that matches..so we can have muticast delegates
2.which method is invoked is postponed until runtime
3 Delegates are the basis for events

Addressof: this represents the address of the method being called by the delegate
ex: delegateobject=Addressof MyMethodOne

Invoke: This method invokes the  method matching the delegates signature

delegateobject.Invoke("MyStringArgument")



The Delegate statement defines the parameter types and return type of a delegate class. Any procedure with matching parameters types and return type may be used to create an instance of this delegate class. The procedure can then later be invoked by means of the delegate instance, by calling the delegate's Invoke method.

Delegates can be declared at the namespace, module, class, or structure level, but not within a procedure.

Each delegate class defines a constructor that is passed the specification of an object method. An argument to a delegate constructor must be an expression of the form:

AddressOf [expression.]methodname

The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified name whose signature matches the signature of the delegate class. The methodname can be either a shared method or an instance method. The methodname is not optional, even if you create a delegate for the default method of the class.

The AddressOf operator creates a function delegate that points to the function specified by procedurename. When the specified procedure is an instance method then the function delegate refers to both the instance and the method. Then, when the function delegate is invoked the specified method of the specified instance is called.

The AddressOf operator can be used as the operand of a delegate constructor or it can be used in a context in which the type of the delegate can be determined by the compiler






Example 1:
The following is a simple example of declaring and using a delegate. Notice that both the delegate, Del, and the associated method, MultiplyNumbers, have the same signature


// Declare a delegate
delegate void Del(int i, double j);

class MathClass
{
    static void Main()
    {
        MathClass m = new MathClass();

        // Delegate instantiation using "MultiplyNumbers"
        Del d = m.MultiplyNumbers;

        // Invoke the delegate object.
        System.Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");
        for (int i = 1; i <= 5; i++)
        {
            d(i, 2);
        }
    }

    // Declare the associated method.
    void MultiplyNumbers(int m, double n)
    {
        System.Console.Write(m * n + " ");
    }
}


Output
Invoking the delegate using 'MultiplyNumbers':

2 4 6 8 10
----------------------------------------------------------

Example 2:

In the following example, one delegate is mapped to both static and instance methods and returns specific information from each.


// Declare a delegate
delegate void Del();

class SampleClass
{
    public void InstanceMethod()
    {
        System.Console.WriteLine("A message from the instance method.");
    }

    static public void StaticMethod()
    {
        System.Console.WriteLine("A message from the static method.");
    }
}

class TestSampleClass
{
    static void Main()
    {
        SampleClass sc = new SampleClass();

        // Map the delegate to the instance method:
        Del d = sc.InstanceMethod;
        d();

        // Map to the static method:
        d = SampleClass.StaticMethod;
        d();
    }
}



Output
A message from the instance method.

A message from the static method.

 

Anonymous Methods

In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.

Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.

For example:


// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };


or


// Create a delegate instance
delegate void Del(int x);

// Instantiate the delegate using an anonymous method
Del d = delegate(int k)
 {
  Console.WriteLine("Iam an Anonymous Method")


 };

 By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
For example, specifying a code block in the place of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead

Example 3

The following example demonstrates the two ways of instantiating a delegate:

Associating the delegate with an anonymous method.

Associating the delegate with a named method (DoWork).

In each case, a message is displayed when the delegate is invoked.


// Declare a delegate
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instatiate the delegate type using an anonymous method:
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call:
        p("The delegate using the anonymous method is called.");

        // The delegate instantiation using a named method "DoWork":
        p = new Printer(TestClass.DoWork);

        // Results from the old style delegate call:
        p("The delegate using the named method is called.");
    }

    // The method associated with the named delegate:
    static void DoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}



Output
The delegate using the anonymous method is called.

The delegate using the named method is called.



 






No comments:

Post a Comment