A delegate is a reference to a method.
It's sometimes confusing how to instantiate a delegate, so I thought to write this.
There are 6 ways to instantiate a delegate as the following example shows:
Example:
delegate int MyDelegate(int a,int b);
public void MyMethod()
{
// simply just assign the method name
MyDelegate myDelegate1 = Add;
// instantiate the delegate and pass the method name
MyDelegate myDelegate2 = new MyDelegate(Add);
// assign an anonymous method (C# 2.0)
MyDelegate myDelegate3 = delegate(int a, int b) { return a + b; };
// assign a lambda expression - format 1 (C# 3.0)
MyDelegate myDelegate4 = (int a,int b) => { return a + b;};
// assign a lambda expression - format 2 (C# 3.0)
MyDelegate myDelegate5 = (a,b) => { return a + b; };
// assign a lambda expression - format 3 (C# 3.0)
MyDelegate myDelegate6 = (a, b) => a + b;
}
public int Add(int a, int b)
{
return a + b;
}
Notes:
Once you have the delegate instance, you can
- Run it e.g. myDelegate1(2, 3);
- Pass the delegate instance to a method
- Return a delegate instance from a method
More info:
No comments:
Post a Comment