I have a C# code like this:
using System;
delegate int anto(int x);
class Anto
{
static void Main()
{
anto a = square;
int result = a(3);
Console.WriteLine(result);
}
static int square(int x)
{
return x*x;
}
}
which output’s : 9. Well I’m a novice in C#, so I started to play around with this code and so when I remove the static keyword from the square method, then I’m getting error like this:
An object reference is required to access non-static member `Anto.square(int)'
Compilation failed: 1 error(s), 0 warnings
what causes this error? So if I use delegates I need the method to be static?
I run this code here
Thanks in advance.
Because
Mainis static, it can only reference other static members. If you removestaticfromsquare, it becomes an instance member, and in thestaticcontext ofMain, there is no instance of any object, so instance members aren’t ‘valid’.Thankfully there’s nothing crazy going on with delegates, it’s just the way
staticworks – it indicates members are global to a type and not an instance of that type.