-3

namespace DelegatePractise1 {

public delegate int AddDelegate(int x, int y);

class Calculator
{
    MathOps opsObj = new MathOps();
    static void Main(string[] args)
    {

        AddDelegate addDelInstance = new AddDelegate(opsObj.Add);//getting error here 
        int sum = addDelInstance(2, 3);
        Console.WriteLine("{0} sum", sum);
        Console.Read();

    }
}

public class MathOps
{
     public int Add(int x, int y)
    {
        return x + y;
    }
}

}

when i initialize the object 'opsObj' inside the main then the error doesn't come anymore. Can you explain why do i need to include the object initialization inside the main for this case. I am new to oop concept. Thanks in advance

2 Answers2

0

you cant use non static object in static main method so convert it to static to make it work or add new class having all the logic this will solve the issue

static MathOps opsObj = new MathOps();
moath naji
  • 663
  • 1
  • 4
  • 20
-1

You can simply assign delegate like this:

 AddDelegate addDelInstance = opsObj.Add;
Gauravsa
  • 6,330
  • 2
  • 21
  • 30