Why can't I call a public method in another class?

Harris picture Harris · Dec 1, 2008 · Viewed 134.2k times · Source

I have got these two classes interacting and I am trying to call four different classes from class one for use in class two.

The methods are public and they do return values but for some reason there is not a connection being made. The error I get when I try is: "An object reference is required for the nonstatic field, method, or property 'GradeBook.[method I want called]'"


I have everything initialized. I don't want to create the methods as static. I read over the specifics of my assignment again and I'm not even supposed to but I can't seem to get this to work anyway I word it.

myGradeBook.[method] GraceBook.[method]

It all seems to create errors.

The current errors:

The best overloaded method match or 'System.Console.WriteLine(string, object)' has some invalid arguments.

Arugment '2': cannot convert from 'method group' to 'object'

I'm not even sur what those mean....

EDIT: I just fixed that problem thanks to the Step Into feature of Visual Studio. I don't know why it took me so long to use it.

Answer

JaredPar picture JaredPar · Dec 1, 2008

You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example

class Example {
  public static string NonInstanceMethod() {
    return "static";
  }
  public string InstanceMethod() { 
    return "non-static";
  }
}

static void SomeMethod() {
  Console.WriteLine(Example.NonInstanceMethod());
  Console.WriteLine(Example.InstanceMethod());  // Does not compile
  Example v1 = new Example();
  Console.WriteLine(v1.InstanceMethod());
}