Delegates in C#
- Delegates are similar to function’s pointer, but it is type-safe
- In C/C++, function’s pointer is only a memory addresses nothing else. It does not provide any information about return type, parameters and function calling convention; due to which function pointer are not type-safe.
- A calling function describes how arguments are passed and values return by functions.
- Delegate call other functions, without knowing who is calling
- Delegate signature contains ‘delegate’ keyword, return type, delegate name (identifier) and parameters that the function takes.
- Three steps:
- Define signature of delegate (declaration)
- define which method will call by this delegate (instantiation)
- calling delegate (invocation)
- Multicasting allows calling multiple methods (functions) by invoking single delegates. It maintain list of functions to call and can achieve by
mydelegate = null;
mydelegate = mydelegate + Delegate(function);
mydelegate = mydelegate + Delegate(another function);