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:
Syntax of using 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.
//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");
Technorati Tags: .NET Framework, C# .NET
No comments:
Post a Comment