I was trying to figure out if I can call a method in its own class (I believe we can) so I created some very simple code:
public class CalMethod
{
int x;
int y;
public int Calculator(int x, int y)
{
return x + y;
}
int result = Calculator(2,3);
}
When I try to do int result= Calculator (2,3);
I saw an error: a field initializer cannot reference the non-static field, method or property. Why this Calculator method needs to be static to be called in its own class? -yes I was trying to do a console app, but this class is not the main class from the program project.
And another thing that confuses me is that I was not able to find 'Calculator' from the list in its own class when typing 'Cal..', when the method is non-static. So I have to create a constructor of this class, and instantiating a new object to allow me to use a non-static method?
Please help. Thank you!
The call for int result = Calculator(2,3);
should be inside a method, in C# any code should be inside a class method
public class CalMethod
{
int x;
int y;
public int Calculator(int x, int y)
{
return x + y;
}
public void TheClient()
{
int result = Calculator(2,3);
}
}