0

Im trying to call this calculator function:

public static void Main(string[] args) {
    int answer = calculate(int a, int b);
    Console.WriteLine(answer);
}

public int calculate(int a, int b) {
    return a + b;
}

but I keep getting an error about making a non-static reference

3 Answers3

1

The reason you can't call your function is because you can't call a non static function from a static function, try adding the static keyword to your calculate function header

acornTime
  • 278
  • 1
  • 15
  • 1
    How would I call it without making it static? – Generic Game Development Apr 12 '22 at 02:31
  • You could make a new object of the class that you are writing in, then call it from that. static means that the variable, or method belongs to the class, and not the object of the class, so you can only call the nonstatic member from an object. you could try the following line: MyClass object = new MyClass(); object.calculate(1, 2); – acornTime Apr 12 '22 at 02:32
  • @GenericGameDevelopment - In this case, because the function is pure, you should make it static. If it relied on state then you wouldn't. – Enigmativity Apr 12 '22 at 04:45
1

instance member function cannot be called from static function, so you need to make other function static aswell

public static void Main(string[] args) {
int answer = calculate(int a, int b);
Console.WriteLine(answer);
}

public static int calculate(int a, int b) {
  return a + b;
}

to call it without making it static you need to create object of the class for example

class Example{

public static void Main(string[] args) {
Example example = new Example();
int answer = example.calculate(int a, int b);
Console.WriteLine(answer);
}

public int calculate(int a, int b) {
  return a + b;
}


}
ahtasham nazeer
  • 137
  • 1
  • 7
1

The static keyword means the method does not require an instance of the class in order to be invoked. For example:

MyClass.MyMethod();  // can be called without using the new keyword

Conversely, a non-static method does require an instance of the class in order to be invoked. For example:

var myInstance = new MyClass();  // create instance of class
myInstance.MyMethod();  // then call non-static method

If you think about it for a moment, you can see why a static method cannot call a non-static method. Static methods may be used when the method does not need access to instance level variables or methods. If your static method does need access to the non-static method you have 2 options:

  1. remove the static keyword (EDIT: woops you are calling directly from main so this isn't possible in this case since main must be static. It usually is though)
  2. make the other method static
Timothy Jannace
  • 1,401
  • 12
  • 18