luckyluke
luckyluke

Reputation: 654

can delegates called on instance methods?

Can a delegate be called only on static methods. I ran below code and got error as Method name expected at lines

NuOp nuopAdd = new NuOp (x.Addition(324324, 4324324));

NuOp nuopMultiply = new NuOp(x.Multiplication(4324, 24234));

namespace DelegateEtAl
{
    public delegate double NuOp(double a, double b);

    class Program
    {
        static void Main(string[] args)
        {
            Mop x = new Mop();
            NuOp nuopAdd = new NuOp   (x.Addition(324324, 4324324));
            NuOp nuopMultiply = new NuOp(x.Multiplication(4324, 24234));

            Console.Out.WriteLine(nuopAdd);
            Console.Out.WriteLine(nuopMultiply);
        }
    }

    public class Mop
    {
        public double Addition(double opA, double opB)
        {
            return opA + opB;
        }

        public double Multiplication(double opA, double opB)
        {
            return opA + opB;
        }
    }
}

When googled all the examples i found were dealing with only static methods. but the below link states

https://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx

For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance.

Thanks.

Upvotes: 1

Views: 1387

Answers (1)

Christos
Christos

Reputation: 53958

You can call a delegate in either a static or not static method. There isn't any such a restriction. However, you have to do it as below:

NuOp nuopAdd = x.Addition;
NuOp nuopMultiply = x.Multiplication;

Console.Out.WriteLine(nuopAdd(324324, 4324324));
Console.Out.WriteLine(nuopMultiply(4324, 24234));

The problem with the way you used your delegates is the fact that you didn't initialized them correctly. This is clear if you read the definition of a delegate here:

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

For further info in how we use a delegate please have a look here.

In a few words, the delegate NuOp can point to any method, which takes two parameters of type double and return a double. In order you instatiate you delegate NuOp you just jave to assign the signature of such a method in NuOp like above.

Upvotes: 1

Related Questions