I'm trying to call a method from another class with a console application. The class I try to call isn't static.
class Program
{
static void Main(string[] args)
{
Program p = new Program();
var myString = p.NonStaticMethod();
}
public string NonStaticMethod()
{
return MyNewClass.MyStringMethod(); //Cannot call non static method
}
}
class MyNewClass
{
public string MyStringMethod()
{
return "method called";
}
}
I get the error:
Cannot access non-static method "MyStringMethod" in a static context.
This works if I move the MyStringMethod to the class program. How could I succeed in doing this? I cannot make the class static nor the method.
Non static methods need an instance. You should create it the same way you create a Program to call its non static method.
Just like you create an instance of the Program class to call the NonStaticMethod, you must create an instance of MyNewClass:
If you want to call a member function of a non-static class then you have to create its instance and then call its required function.
So for calling MyStringMethod() of non-static class MyNewClass, do this:
You need to create an Instance of
MyNewClass
Non static class need an instance to access its members.
Create the instance inside the static Main method and call non static class member: