views:

327

answers:

6

I have a static function in a class.

whenever I try to use non static data member, I get following compile error.

An object reference is required for the nonstatic field, method, or property member

Why is it behaving like that?

+2  A: 

A static method cannot directly access any non-static member variables of a class.

After all : a static method can be called without an instance of the class even being in existance. How do you want to access a member variable on a non-existing instance??

(of course, as Mehrdad pointed out: you could pass an instance of your class to a static method and access everything on that instance - but that's not what you're talking about, right?)

marc_s
+3  A: 

Instance methods rely on state of that particular instance in order to run.

Let's say you had this class which has the scenario you describe:

class Person
{
    static PrintName()
    {
        // Not legal, but let's say it is for now.
        Console.WriteLine(Name);
    }

    private Name { get; set; }
}

Hopefully, the problem is apparent now. Because Name is an instance member, you need an actual instance of the class, since Name can be different across different instances.

Because of this, the static method, which is not attached to an instance, doesn't know which instance to use. You have to be explicit in specifying which one.

casperOne
+17  A: 

A non-static member belongs to an instance. It's meaningless without somehow resolving which instance of a class you are talking about. In a static context, you don't have an instance, that's why you can't access a non-static member without explicitly mentioning an object reference.

In fact, you can access a non-static member in a static context by specifying the object reference explicitly:

class HelloWorld {
   int i;
   public HelloWorld(int i) { this.i = i; }
   public static void Print(HelloWorld instance) {
      Console.WriteLine(instance.i);
   }
}

var test = new HelloWorld(1);
var test2 = new HelloWorld(2);
HelloWorld.Print(test);

Without explicitly referring to the instance in the Print method, how would it know it should print 1 and not 2?

Mehrdad Afshari
ok, sure - a static method can access stuff on an instance passed in as a parameter.... good point, but I guess not what the OP really was talking about....
marc_s
@marc_s: I know what OP is wondering about. I think this way of answering clarifies the reason more effectively. It proves it's not some kind of arbitrary limitation imposed on static methods but the only way it can work out.
Mehrdad Afshari
+1, its a common scenario, for example DependencyPropertyChanged call backs.
AnthonyWJones
+2  A: 

Static functions can only use static members, and call static functions.

As mentioned, a static function can operate on a class instance, but not from within a class instance (for lack of a more descriptive word). For example:

class MyClass
{
    public int x;
    public static int y;

    public static void TestFunc()
    {
        x = 5; // Invalid, because there is no 'this' context here
        y = 5; // Valid, because y is not associated with an object instance
    }

    public static void TestFunc2(MyClass instance)
    {
        instance.x = 5; // Valid
        instance.y = 5; // Invalid in C# (valid w/ a warning in VB.NET)
    }
}
Jon Seigel
A: 

You can't access non-static data from a static function. This is because the static function can be called irrespective of whether there are any instantiated objects of the class. The non-static data, however, is dependent on a specific object (instantiation) of the class. Since you can't be sure that there are any objects instantiated when calling a static function, it is illogical (and therefore not allowed) to access non-static data from it.

This question has been asked several times on SO in different forms / for different languages:

froadie
Your first link is incorrect - it points to the Java question
ChrisF
@ChrisF - Thanks. Corrected.
froadie
A: 

The definition of a "non static data member" would be an "instance data member". In other words non static members belong to a created instance of your class.

A static method does not run in the context of any specific instance of the class. Hence when you ask such a method to use a non static member it will have no idea which of the 0 or more instances of the class it should try to get the data from.

AnthonyWJones