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;
}
}
A static method cannot tell to which particular object the non-static member belongs to. Since there is no existing object, the non-static method doesn't belong to any object. Hence there is no way a non-static method can be referenced from static context.
“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.
Static delegates are not without limitations. They can only refer to static functions; member methods on objects are not permitted because there is no place to store the pointer to the object. Furthermore, static delegates cannot be chained to other delegates.
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With