Wednesday, April 6, 2011

Delegates in C#.

Delegates in C# are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.
Here are some features of delegates:
  • A delegate represents a class.
  • A delegate is type-safe.
  • We can use delegates both for static and instance methods
  • We can combine multiple delegates into a single delegate.
  • Delegates are often used in event-based programming, such as publish/subscribe.
  • We can use delegates in asynchronous-style programming.
  • We can define delegates inside or outside of classes. 

Syntax of using delegates

//Declaring delegate
delegate void SampleDelegate(string message);

// declare method with same signature:
static void SampleDelegateMethod(string message) { Console.WriteLine(message); }

// create delegate object
SampleDelegate d1 = SampleDelegateMethod;

// Invoke method with delegate
d1("my program");

No comments:

Post a Comment

Ajax CalendarExtender displaying at wrong position in Chrome

< script type ="text/javascript" language ="javascript">     function onCalendarShown(sender, args)...