Wednesday, July 1, 2009

What is the difference between static and class method

static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.

C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).

In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?

The methods use a similar principle. They should be used for procedures for which it is impractical to do within an instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it is)

However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)

No comments:

Post a Comment

 
Locations of visitors to this page