I was just trying to understand delegates using the following code.
public class delegatesEx
{
public delegate int Mydelegate(int first, int second);
public int add(int first, int second)
{
return first + second;
}
public int sub(int first, int second)
{
return first - second;
}
}
Here is my main method
Console.WriteLine("******** Delegates ************");
delegatesEx.Mydelegate myAddDelegates = new delegatesEx.Mydelegate(new delegatesEx().add);
int addRes = myAddDelegates(3, 2);
Console.WriteLine("Add :" + addRes);
delegatesEx.Mydelegate mySubDelegates = new delegatesEx.Mydelegate(new delegatesEx().sub);
int subRes = mySubDelegates(3, 2);
Console.WriteLine("Sub :" + subRes);
I didn't declare delegate to be static but i was able to access it using the Class name. How is it possible?
You're not declaring a variable but a new delegate type named MyDelegate in the class. As this is a type declaration static and instance doesn't really apply. In your main method you declare an actual variable of that type. Similarly, you could have created both instance and static members of the type MyDelegate on the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With