Search code examples
c#.netvisual-studio-2005functiondelegates

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;
    }
}

Solution

  • 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; 
        } 
    }