About Delegate in .NET 4.0

I got this post from http://sunnywang.blog.com/2011/10/26/translation-about-delegate-in-net-4-0/. I think that this post is helpful for .NET learning, so I share it with you. Also, I have gotten the right to sharing it from blog's owner.

*****************************************

Delegate in .NET has the similar function to Method-Pointer in C or C++. We can call delegate to complete one function as calling method or return result of one type. But, delegate is more improved. It is data interface, including pointers to call object and method. The defined delegate in .NET needs to inherit from MulticastDelegate, which includes several called methods.

1. Delegate Definition

The following C# code is used to define delegate.

public delegate void DoSomething(int times);

There are five parts of delegate definition.

   1) public:  delegate accessibility
   2) delegate: define one delegate
   3) void: return value of delegate definition method
   4) DoSomething: delegate name
   5) (int times) parameter list of delegate method. The list includes ref parameter, out parameter, and parms variable amount parameter. Note: if there are several called method, it just can return the calculated value of the last delegate method which is run successfully by using out parameter.

It is easy to define delegate in C#. We just need to add a delegate keyword at font of method definition return value.

As is known, all the users defined delegates are inherit from MulticastDelegate. Because it is a class, so customized delegate is a class as well. The following code can verify our judgement.

.class public auto ansi sealed delegates.DoSomething
 extends [mscorlib]System.MulticastDelegate
{
 // Methods
 .method public hidebysig specialname rtspecialname
  instance void .ctor (
   object 'object',
   native int 'method'
  ) runtime managed
 {
 } // end of method DoSomething::.ctor

 .method public hidebysig newslot virtual
  instance void Invoke (
   int32 times
  ) runtime managed
 {

 } // end of method DoSomething::Invoke


 .method public hidebysig newslot virtual
  instance class [mscorlib]System.IAsyncResult BeginInvoke (
   int32 times,
   class [mscorlib]System.AsyncCallback callback,
   object 'object'
  ) runtime managed
 {

 

 } // end of method DoSomething::BeginInvoke


 .method public hidebysig newslot virtual
  instance void EndInvoke (
   class [mscorlib]System.IAsyncResult result
  ) runtime managed
 {

 } // end of method DoSomething::EndInvoke

} // end of class delegates.DoSomething

 

2. Delegate Usage

There are three types of delegate in .NET, method, anonymous method and lambda expression. The following code shows how to use delegate by method definition.

using System;

namespace delegates
{
 public delegate void DoSomething(int times);

    class Program
    {
        static void Main(string[] args)
        {
            //Declare Delegate Variable and Assign Value
            DoSomething @do = DoA;
            //Use + or += to Add Method for Delegate
            @do += DoB;
            //Run Methods of Delegate According to Sequence which We Add Delegate
            @do(1);
            //Use - or -= to Remove Delegate
            @do -= DoA;
            @do(2);

            @do -= DoB;
            //Delegate Can Be Called after Removing All the Methods as well.
            @do(3);

            Console.Read();
        }
       //Define a Method to Delegate the Same Parameter and Return Value
        static void DoA(int times)
        {
            Console.WriteLine("Do A {0}", times);
        }


        //Define a Method to Delegate the Same Parameter and Return Value
        static void DoB(int times)
        {
            Console.WriteLine("Do B {0}", times);
        }
    }
}

In the above code, we define variable @do of DoSomething and assign value to it with DoA method directly. Then, use + or += to add another method for the delegate. Also, we can remove methods by using - or -=.

Note: we need to pay attention to run addition and subtraction.

I. Writing Style of Delegate Declaration

Generally speaking, we can use the following writing.

DoSomething @do = DoA;

It is simple writing and just can be used in .NET 2.0 and last versions. In .NET 1.x, we need to write as following:

DoSomething @do = new DoSomething(DoA);

We should assign @do DoA to plus DoB when declaring.

DoSomething @do = DoA + DoB;

But this writing is useless so that we must use writing in .NET 1.x.

DoSomething @do = new DoSomething(DoA) + new DoSomething(DoB);

II. What Will Happen If Subtracting Nonexistent Method in Delegate?

Move to the following code:

DoSomething @do = DoA;
@do -= DoB;

In the first line, I declare @do and assign DoA to it. In the second line, I try to subtract DoB, which doesn't exist in method list, from @do. What will happen? There is no error given and DoA method is run correctly when calling @do. It is observed that programm can be run normally when subtracting one nonexistent method in delegate.

III. What Will Happen If all the Delegates Are Subtracted?

Move to the following code:

DoSomething @do = new DoSomething(DoA) + new DoSomething(DoB);
@do -= DoA;
@do -= DoB;
@do(1);

The code can be complied successfully, but NullReferenceException will appear when running. Therefore, we must be careful when doing subtraction for delegate.

3. Delegate Covariation

Covariation is that method parameter and return value which realize delegate can be transformed implicitly.

public delegate void DoIt(string task);

class Test
{
    static void Main(string[] args)
    {
        //DoIt Declaration. It Is Valid to Assign Parameter a Looser Method
        DoIt doIt = new DoIt(DoItImpl);
        doIt("hello");
    }

    //Looser than Delegate Defining Parameter. String Can Be Converted to object Implicitly.
    static void DoItImpl(object task)
    {
        Console.WriteLine("DoItImpl {0}",task);
    }
}

Because delegate string can be converted to DoItUmpl parameter type, object implicitly, so the above code is valid when using.

 

Original Source: http://www.cnblogs.com/yukaizhao/archive/2011/10/21/2220448.html

 

Recommendation (Component Working on Office for Silverlight and .NET):

Spire.Office: http://www.e-iceblue.com/Introduce/spire-office-for-net.html 

Spire.Doc: http://www.e-iceblue.com/Introduce/word-for-net-introduce.html

Spire.XLS: http://www.e-iceblue.com/Introduce/excel-for-net-introduce.html

Spire.PDF: http://www.e-iceblue.com/Introduce/pdf-for-net-introduce.html

Advertisements

Author: janewdaisy

.NET Program Beginner. Share methods about how to use C#/VB.NET to export data, operate Word, Excel, PDF and other useful skills.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s