Why can't a delegate refer to a non-static method when used in a static method?
Solution 1
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;
}
}
Solution 2
In this case, because you aren't creating an instance of any class, the only alternative is a static function. Were you to instantiate an object of type Program, then you could use an instance method instead.
Solution 3
Delegates basically follow the same rules as methods. In the example provided your delegate must be static because you are calling it from a static method. In the same vein this will not work:
static void Main(string[] args)
{
int Res = Add(3, 4);
Console.WriteLine(Res);
}
public int Add(int a, int b)
{
int result;
result = a + b;
return result;
}
However if you moved things into a non static context like this:
class MyClass
{
public MyClass()
{
Fun F1 = new Fun(Add);
int Res = F1(2, 3);
Console.WriteLine(Res);
}
public int Add(int a, int b)
{
int result;
result = a + b;
return result;
}
}
You can have a delegate with a non-static method.
Sundhas
Updated on June 13, 2020Comments
-
Sundhas almost 4 years
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; } }