Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Was delegates static by default?

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?

like image 378
Gopi Avatar asked Apr 14 '26 00:04

Gopi


1 Answers

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.

like image 147
Brian Rasmussen Avatar answered Apr 15 '26 14:04

Brian Rasmussen