Simple Delegates With Examples.
Delegates have the following properties:
- Delegates are similar to C++ function pointers, but are type safe.
- Delegates allow methods to be passed as parameters.
- Delegates can be used to define callback methods.
- Delegates can be chained together; for example, multiple methods can be called on a single event.
- Methods don't need to match the delegate signature exactly.
- Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code that can call the referenced method, without having to know at compile time which method will be invoked.
- An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
Example 1
Before applying the delegate:
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- GetData("Mahesh");
- }
- }
- public void GetData(string Name)
- {
- lblName.Text = Name;
- }
Output
Mahesh
After applying the delegate:
- public delegate void MyDelegare(string var);
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- MyDelegare objMyDelegare = new MyDelegare(GetData);
- objMyDelegare("Mahesh");
- }
- }
- public void GetData(string Name)
- {
- lblName.Text = Name;
- }

Praveen VeeraPosted Oct 1, 2019, 11:12 PM
You mentioned that Methods don't need to match the delegate signature exactly.Is it correct.Because in another article i read that delegate and method signature should match,hence it is called as type safe.
Sam HobbsPosted Mar 15, 2013, 6:48 PM
I am interested in understanding how C++ function pointers are not type safe when used properly. Obviously assigning a C++ function pointer to a void * is not proper, but unless something like that is done I do not know how they are not type safe.