views:

265

answers:

6

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:

An object reference is required for the non-static field, method, or property "ClassName.MethodName()"

Can someone please briefly describe why? including other things that might be related to this.

EDIT: Thanks for the responses, guys!

This was a small fault on my part, let me try and explain. The class was a part of a factory, and the factory has instance of all the classes. But this method was NoWhere to be found because it wasn't part of the interface thats implemented by the class, instead it was just added as an helper function.

The answer were also very helpful!

+16  A: 

A non-static method requires an instance of the class. Unless you have passed in an instance, or created an instance in your method, you cannot call a non-static method, as you have no idea what instance of the class that method should operate on.

Yann Ramin
+2  A: 

Within a static method, you do not have an instance of the class. So it will be impossible to call an instance method on an instance when no instance exists.

Wallace Breza
A: 

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.

jer
A: 

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.

xtofl
+1  A: 

In order to call non static method (i.e. instance method) you must have a instance of object of the method before you can call the said method.

What you are actually trying to do is this. Note the this object in Method1. You do not have this available in static methods.

static void Method1() {
   this.Method2()
}

void Method2() { }
Juha Syrjälä
Thanks! This makes sense
VoodooChild
+1  A: 

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.

Tim Coker