14

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?

danben
  • 80,905
  • 18
  • 123
  • 145
Novice Developer
  • 4,489
  • 11
  • 39
  • 42
  • Almost-duplicate: http://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static-c – Jon Seigel Feb 17 '10 at 18:27
  • @casperOne: Please post duplicate suggestions as comments rather than rewriting the question. There is a reason 5 close votes are required. – danben Feb 17 '10 at 18:28
  • 2
    And the title is somewhat misleading... You can access static members from non-static functions. – froadie Feb 17 '10 at 18:29
  • @froadie - Of course, by asking the question, he demonstrates that he doesn't understand the concepts of static vs. instance, and wouldn't think the title is misleading. – Nick Feb 17 '10 at 18:50
  • @Nick: yes i dont know the concept. thank you for bearing me. – Novice Developer Feb 17 '10 at 19:05
  • 2
    @Nick - That's why he's asking the question; he doesn't understand it and wants to. @novicedeveloper - maybe consider renaming the title to "Why can't I access non-static members from a static function?" – froadie Feb 17 '10 at 19:33

6 Answers6

20

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
  • 414,610
  • 91
  • 852
  • 789
  • 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 Feb 17 '10 at 18:24
  • 4
    @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 Feb 17 '10 at 18:25
  • +1, its a common scenario, for example DependencyPropertyChanged call backs. – AnthonyWJones Feb 17 '10 at 18:38
5

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
  • 73,706
  • 19
  • 184
  • 253
2

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
  • 732,580
  • 175
  • 1,330
  • 1,459
2

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
  • 12,251
  • 8
  • 58
  • 92
1

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:

Community
  • 1
  • 1
froadie
  • 79,995
  • 75
  • 166
  • 235
1

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
  • 187,081
  • 35
  • 232
  • 306