tags:

views:

84

answers:

4

If delegates are Abstract then how it allows to create object

+4  A: 

Here's a link to one of the best essays on C# delegates I have found, and the author does a great job of providing an entertaining and informative walkthrough of how delegates work and why we use them.

http://www.sellsbrothers.com/writing/default.aspx?content=delegates.htm

Bob Palmer
Oh yes, the bedtime story. It's a classic for me :)
o.k.w
+3  A: 

delegate is a type safe function pointer. It is a reference type in C#.

 delegate result-type identifier ([parameters]);  

However the Delegate class is not a delegate type, it's a class used to derive delegate types, thus it is abstract (check for more clarification).

Aggelos Mpimpoudis
+1  A: 

A delegate looks like a typesafe function pointer, of course to understand that you'd need to know what a function pointer is and why typesafety is important, but it's more than that.

Under the covers a delegate is a class with an Invoke method, the Invoke method is created at compile time to have the same signature as the delegate definition. So if I do

delegate int MyDelegate(string s);

I'd end up with something like

class MyDelegate : MulticastDelegate
{
    int Invoke(string s) {...}
}

I can use this in code like this

int SomeFunc(string s)
{
    // do something with s and return an int
}

MyDelegate del = new MyDelegate(SomeFunc);

then either

int a = del.Invoke("Foo");

or simply

int a = del("Foo");

It's this last usage that makes it look like a function pointer ('del' is pointing to the SomeFunc function), and it's typesafe because it only takes and returns the types defined (the rules are a bit more complicated than this).

You also now have other ways of calling the delegate notable anonymous methods and lambdas but that's beyond the scope of this

A lot of this happens with compiler magic, for example turning the delegate definition into a class definition and turning the call to the method into a call to Invoke.

HTH

Kevin Jones
A: 

Here's an excellent article about delegates and later on discusses Lambda expressions highlighting the relationship between them.

Hope this helps, Best regards, Tom.

tommieb75