How delegate is defined in C#?

It could be a surprise (for me it was) but delegate is a type-safe object that point to another method or methods.  So if delegate is an instance of class how this class looks? Answer is really simple because when C# compiler processes delegate types, it automatically generate a sealed class.

Let’s show an example for delegate that can point to any method taking integers and returning also an integer:

public delegate int MyDelegate(int a, int b);

Below we can see how compiler generated class for our delegate:

sealed class MyDelegate : System.MulticastDelegate
{
public MyDelegate(object tagret, uint functionAddress);
public int Invoke(int a, int b);
public IAsyncResult BeginInvoke(int a, int b, AsyncCallback cb, object state);
public int EndInvoke(IAsyncResult result);
}

What these methods doing?

  • Invoke – invoke each method maintained by the delegate type in synchronous manner
  • BeginInvoke – provide the ability to call the current method asynchronously.
  • EndInvoke – as above.

Notice that the generate class MyDelegate is delivered from System.MulticastDelegate.

Delegates can also handing methods that contains out or ref parameters:

public delegate int MyDelegate(ref int a, out int b, bool c);

Generated class:

sealed class MyDelegate : System.MulticastDelegate
{
public MyDelegate(object tagret, uint functionAddress);
public int Invoke(ref int a, out int b, bool c);
public IAsyncResult BeginInvoke(ref int a, out int b, bool c, AsyncCallback cb, object state);
public int EndInvoke(ref int a, out int b, IAsyncResult result);
}

Notice difference: As you expect signatures contains out/ref arguments. But method EndInvoke() now also includes the set of all out/ref arguments.

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