Sunday 24 February 2008

Delegate in C#

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.


List members = new List();
members.Sort(delegate(IFolderExplorerHierarchyMember member1, IFolderExplorerHierarchyMember member2)
{
return member1.Name.CompareTo(member2.Name);
});


Brilliant article: http://www.c-sharpcorner.com/UploadFile/arulchinnappan/Delegate_109152005080029AM/Delegate_1.aspx?ArticleID=42f8981b-72d2-441f-a95f-48dcbb93dbf5

A delegate can hold reference/s to one more more functions and invoke them as and when needed.

A delegate needs the method's name and its parameters (input and output variables) when we create a delegate. But delegate is not a standalone construction. it's a class. Any delegate is inherited from base delegate class of .NET class library when it is declared. This can be from either of the two classes from System.Delegate or System.MulticastDelegate.

If the delegate contains a return type of void, then it is automatically aliased to the type of System.MulticastDelegate. This can support multiple functions with a += operator. If the delegate contains a non-void return type then it is aliased to System.Delegate class and it cannot support multiple methods.

Source: http://www.codersource.net/csharp_delegates_events.html

No comments: