Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a delegate refer to a non-static method when used in a static method?

Why is it necessary to make a function STATIC while using delegates in C# ?

class Program
{
    delegate int Fun (int a, int b);
    static void Main(string[] args)
    {
        Fun F1 = new Fun(Add);
        int Res= F1(2,3);
        Console.WriteLine(Res);
    }

   **static public int Add(int a, int b)** 
    {
        int result;
        result = a + b;
        return result;
    }
}
like image 499
Sundhas Avatar asked Feb 19 '10 19:02

Sundhas


People also ask

Why can't a static method refer to non-static members of the class?

A static method cannot tell to which particular object the non-static member belongs to. Since there is no existing object, the non-static method doesn't belong to any object. Hence there is no way a non-static method can be referenced from static context.

Can we call a non-static method from a non-static method?

“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.

Can a delegate be static?

Static delegates are not without limitations. They can only refer to static functions; member methods on objects are not permitted because there is no place to store the pointer to the object. Furthermore, static delegates cannot be chained to other delegates.

How do you call a non-static method in another method?

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.


1 Answers

It's not "necessary". But your Main method is static, so it can't call a non-static method. Try something like this (this isn't really a good way to do things—you really should create a new class, but it doesn't change your sample much):

class Program 
{ 
    delegate int Fun (int a, int b); 
    void Execute()
    {
       Fun F1 = new Fun(Add); 
       int Res= F1(2,3); 
       Console.WriteLine(Res); 
    }

    static void Main(string[] args) 
    { 
        var program = new Program();
        program.Execute();
    } 

    int Add(int a, int b)
    { 
        int result; 
        result = a + b; 
        return result; 
    } 
}
like image 189
Ðаn Avatar answered Sep 27 '22 18:09

Ðаn