Difference between revisions of "C Sharp Delegates"
m (1 revision imported) |
|||
| Line 3: | Line 3: | ||
[[Category:Entity Framework]] | [[Category:Entity Framework]] | ||
[[Category:Linq]] | [[Category:Linq]] | ||
| + | == What is a Delegate? == | ||
| + | A delegate is a type-safe function pointer in C#. It allows you to encapsulate a method with a specific signature and return type, enabling you to pass methods as parameters or store them in variables. Delegates provide the foundation for events and callback methods, making your code more modular and flexible. | ||
== Why do we need C# delegates == | == Why do we need C# delegates == | ||
| Line 11: | Line 13: | ||
* You want to pass method as a parameter. | * You want to pass method as a parameter. | ||
* You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method. | * You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method. | ||
| + | |||
| + | == Sample == | ||
| + | <pre> | ||
| + | class Program | ||
| + | { | ||
| + | public delegate int Operation(int a, int b); | ||
| + | |||
| + | public static int Add(int a, int b) | ||
| + | { | ||
| + | return a + b; | ||
| + | } | ||
| + | |||
| + | public static int Subtract(int a, int b) | ||
| + | { | ||
| + | return a - b; | ||
| + | } | ||
| + | |||
| + | static void Main() | ||
| + | { | ||
| + | Operation op = Add; // Assign the Add method to the delegate | ||
| + | Console.WriteLine(op(3, 4)); // Outputs 7 | ||
| + | |||
| + | op = Subtract; // Reassign to Subtract method | ||
| + | Console.WriteLine(op(10, 4)); // Outputs 6 | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
| + | |||
| + | == Events == | ||
| + | An event in C# is a way for a class to provide notifications to clients of that class when something of interest occurs. Events are built upon delegates and provide a more structured way to handle notification patterns. | ||
| + | |||
| + | == Declaring and Raising an Event == | ||
| + | <pre> | ||
| + | public class Alarm | ||
| + | { | ||
| + | public delegate void AlarmEventHandler(string location); | ||
| + | public event AlarmEventHandler OnAlarmRaised; | ||
| + | |||
| + | public void RaiseAlarm(string location) | ||
| + | { | ||
| + | OnAlarmRaised?.Invoke(location); | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
| + | Here, the Alarm class declares an event OnAlarmRaised using the AlarmEventHandler delegate. The RaiseAlarm method raises the event, notifying any subscribers. | ||
| + | |||
| + | == Subscribing to Events == | ||
| + | <pre> | ||
| + | class Program | ||
| + | { | ||
| + | static void Main() | ||
| + | { | ||
| + | Alarm alarm = new Alarm(); | ||
| + | alarm.OnAlarmRaised += AlarmRaisedHandler; // Subscribe to the event | ||
| + | |||
| + | alarm.RaiseAlarm("Living Room"); | ||
| + | } | ||
| + | |||
| + | static void AlarmRaisedHandler(string location) | ||
| + | { | ||
| + | Console.WriteLine($"Alarm raised at: {location}"); | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
| + | |||
| + | == Real-World Use Cases == | ||
| + | * GUI Applications: Events are commonly used in GUI applications to handle user actions like button clicks, mouse movements, or key presses. | ||
| + | * Asynchronous Programming: Delegates and events are crucial in asynchronous programming, enabling callback methods when tasks are completed. | ||
| + | * Custom Event Systems: You can create custom event systems for specific application needs, allowing different parts of your application to communicate without being tightly coupled. | ||
| + | == Best Practices == | ||
| + | * Use EventHandler or EventHandler<T>: In most cases, it’s best to use the EventHandler delegate or the generic EventHandler<T> instead of custom delegates for events. This follows .NET conventions and improves code readability. | ||
| + | * Check for Null: Always check if the event is null (i.e., no subscribers) before raising it to avoid NullReferenceException. | ||
| + | * Prefer Events Over Direct Delegate Exposure: While exposing delegates directly is possible, it’s better to use events, as they provide better encapsulation and control over how clients interact with your class. | ||
| + | == Conclusion == | ||
| + | Delegates and events are powerful features in C# that enable you to write more modular, reusable, and maintainable code. By understanding how to use them effectively, you can build applications that are responsive, flexible, and easy to extend. | ||
Latest revision as of 14:45, 25 February 2026
Contents
What is a Delegate?
A delegate is a type-safe function pointer in C#. It allows you to encapsulate a method with a specific signature and return type, enabling you to pass methods as parameters or store them in variables. Delegates provide the foundation for events and callback methods, making your code more modular and flexible.
Why do we need C# delegates
- You want to call series of method by using single delegate without writing lot of method calls.
- You want to implement event based system elegantly.
- You want to call two methods same in signature but reside in different classes.
- You want to pass method as a parameter.
- You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method.
Sample
class Program
{
public delegate int Operation(int a, int b);
public static int Add(int a, int b)
{
return a + b;
}
public static int Subtract(int a, int b)
{
return a - b;
}
static void Main()
{
Operation op = Add; // Assign the Add method to the delegate
Console.WriteLine(op(3, 4)); // Outputs 7
op = Subtract; // Reassign to Subtract method
Console.WriteLine(op(10, 4)); // Outputs 6
}
}
Events
An event in C# is a way for a class to provide notifications to clients of that class when something of interest occurs. Events are built upon delegates and provide a more structured way to handle notification patterns.
Declaring and Raising an Event
public class Alarm
{
public delegate void AlarmEventHandler(string location);
public event AlarmEventHandler OnAlarmRaised;
public void RaiseAlarm(string location)
{
OnAlarmRaised?.Invoke(location);
}
}
Here, the Alarm class declares an event OnAlarmRaised using the AlarmEventHandler delegate. The RaiseAlarm method raises the event, notifying any subscribers.
Subscribing to Events
class Program
{
static void Main()
{
Alarm alarm = new Alarm();
alarm.OnAlarmRaised += AlarmRaisedHandler; // Subscribe to the event
alarm.RaiseAlarm("Living Room");
}
static void AlarmRaisedHandler(string location)
{
Console.WriteLine($"Alarm raised at: {location}");
}
}
Real-World Use Cases
- GUI Applications: Events are commonly used in GUI applications to handle user actions like button clicks, mouse movements, or key presses.
- Asynchronous Programming: Delegates and events are crucial in asynchronous programming, enabling callback methods when tasks are completed.
- Custom Event Systems: You can create custom event systems for specific application needs, allowing different parts of your application to communicate without being tightly coupled.
Best Practices
- Use EventHandler or EventHandler<T>: In most cases, it’s best to use the EventHandler delegate or the generic EventHandler<T> instead of custom delegates for events. This follows .NET conventions and improves code readability.
- Check for Null: Always check if the event is null (i.e., no subscribers) before raising it to avoid NullReferenceException.
- Prefer Events Over Direct Delegate Exposure: While exposing delegates directly is possible, it’s better to use events, as they provide better encapsulation and control over how clients interact with your class.
Conclusion
Delegates and events are powerful features in C# that enable you to write more modular, reusable, and maintainable code. By understanding how to use them effectively, you can build applications that are responsive, flexible, and easy to extend.