I tried this:
class Program
{
public delegate int add(int x, int y);
public class ff
{
public static int addNumbers(int x, int y)
{
return x + y;
}
public static int substractNumbers(int x, int y)
{
return x - y;
}
static void Main(string[] args)
{
Delegate delegare = new add(ff.addNumbers);
Console.WriteLine(delegare(3,4));
}
}
I don't see why I'm getting this error"Method name expected". When I use a delegate with a void function it works. Can someone help me?
The type of your delegare
variable is just Delegate
. That could refer to any delegate. In order to invoke a delegate (in the normal way), you should have an expression of the appropriate type.
After fixing the naming conventions and removing the unnecessary nested class - and demonstrating a method group conversion - your code looks like this:
using System;
public delegate int Int32Operation(int x, int y);
class Program
{
public static int AddNumbers(int x, int y)
{
return x + y;
}
public static int SubtractNumbers(int x, int y)
{
return x - y;
}
static void Main(string[] args)
{
Int32Operation op = new Int32Operation(AddNumbers);
Console.WriteLine(op(3, 4)); // Prints 7
op = SubtractNumbers; // Method group conversion
Console.WriteLine(op(3, 4)); // Prints -1
}
}
See more on this question at Stackoverflow