How to Declare Delegates More Simply in C#
In C#, delegate
lets you treat functions as variables. This feature is widely used for callbacks, event handlers, and various kinds of dynamic behavior. However, when you define your own delegate type, it can feel verbose and repetitive.
Traditional Delegate Syntax
// Step 1: Define the delegate type
private delegate void StateCallback();
// Step 2: Declare variables
private StateCallback onStart;
private StateCallback onUpdate;
private StateCallback onComplete;
// Step 3: Assign methods
onStart = () => Debug.Log("Start");
onUpdate = () => Debug.Log("Updating");
onComplete = () => Debug.Log("Done");
As you can see, this approach requires you to define the delegate type first, then declare each variable, and finally assign a method. It works well, but the amount of boilerplate adds up quickly—especially if you have multiple related callbacks.
Using Action
for Simplicity
You can simplify this pattern by using Action
, which is a predefined delegate representing a method that returns void
. Here's the same logic with Action
:
// No type declaration needed
private Action onStart;
private Action onUpdate;
private Action onComplete;
onStart = () => Debug.Log("Start");
onUpdate = () => Debug.Log("Updating");
onComplete = () => Debug.Log("Done");
Since Action
is already defined by the .NET framework, you don’t need to create a new delegate type. This makes your code cleaner and easier to follow.
Predefined Delegate Types
C# provides several built-in delegate types that help you avoid repetitive declarations:
- Action: For methods with no return value.
- Func<T>: For methods that return a value. The last generic parameter is the return type.
- Predicate<T>: A shorthand for
Func<T, bool>
, often used in filters and conditions.
Conclusion
If you need meaningful names for documentation or type distinction, defining a delegate still makes sense.
But for most callbacks, especially when used in series or handled inline, Action
, Func
, and Predicate
let you write more concise and readable code.