Monday, May 24, 2010

Why can’t we use non-static member (variables) in a static method? (C#.NET)?

Because a static method is the same for each and every class. Meaning, each and every class will point to that one single method, which is shared between them.





If you try use a class variable in a static method, you have no way of telling which specific object called this static function (you would know the type of class but not which instance). Because of this, the function wouldn't know which instance the member variable belongs to, so it wouldn't know which instance to make the changes to.





I hope that made sense.

Why can’t we use non-static member (variables) in a static method? (C#.NET)?
a static variable/method represents a variable/method that is used for all instances of a class. When you create a new object using that class, the same copy of the variable/method is used. So creating two objects of your class and changing the value of a variable using a static method changes the value of that same variable across all instances of your class because they are all pointing to the same place in memory.





a non-static member/variable is created as a new/different copy with each instance of the class. So creating two objects of your class and changing the value of the variable in one method doesn't affect the value of that same variable in the other object since they aren't pointing to the same place in memory.





Trying to put a non-static variable inside a static method makes the compiler wonder which instance of this variable should I really be updating? Its also the reason why you shouldn't use static methods using your objects. So if GetWords() is a static method of your Words class and you have an object myWords created from that class, don't do:





myWords.GetWords();





instead do this:





Words.GetWords();
Reply:Before object oriented programming, programmers used to "fake it" for complex projects. They'd created a structure and functions for it like this:





struct MyStruct


{


int myIntValue;


char myCharValue;


}





DoSomethingToMyStruct(MyStruct *this)


{


}





DoSomethingElse(MyStruct *this, int anotherValue)


{


}





In today's object oriented programming, this is still happening behind the scenes. In C#, you are probably familiar with the 'this' variable, which is the current instance of a class -- this variable is always intrisnically passed as the first argument to the method. A call like this in C#:





MyStruct.DoSomething();





is really:





DoSomething(MyStruct);





With that in mind, static methods are not associated with an instance of a class, therefore their is no 'this' reference, and no way to access the values of the class members.

violet

No comments:

Post a Comment