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?
A Static Method can access Static Data because they both exist independently of specific instances of a class.
non-static methods can access any static method and static variable also, without using the object of the class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
Since, static function does not know about object, so, it is impossible for a static function to know on which class object or class instance it is being called. Hence, whenever, we try to call non-static variable from a static function, the compiler flashes an error.
Static methods can't access instance methods and instance variables directly. They must use reference to object. And static method can't use this keyword as there is no instance for 'this' to refer to.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With