I have a static method [Method1] in my class, which calls another method [Method2] in the same class and is not a static method. But this is a no-no. I get this error:
You need an instance of the class class to call the non-static method. You could create an instance of ClassName and call Method2 like so:
public class ClassName
{
public static void Method1()
{
ClassName c = new ClassName();
c.Method2();
}
public void Method2()
{
//dostuff
}
}
The static keyword basically marks a method as being call-able by referencing only its type [ClassName]. All non-static methods have to be referenced via an instance of the object.
The static method by definition is not provided access to a this
. Hence, it cannot call a member method.
If the member method you're trying to call from the static method doesn't need a this
, you can change it into a static method.
Because a "static" method is what's known as a "class method". That is, you dispatch on an object one of two ways in a class-based language like C#, by class or by instance. non-static members can be dispatched to by other non-static members, conversely, static members can be called only be other static members.
Keep in mind, you can get to one from the other, by the "new" mechanism, or visa versa.