Using Static Members
The properties
and methods of a class can be either instance
members or static members. Instance
members are associated with instances of a type, while static members
are considered to be part of the class. You access a static member
through the name of the class in which it is declared. For example,
suppose you have a class named Button and have
instantiated objects of that class named btnUpdate
and btnDelete. Suppose as well that the
Button class has a static method
SomeMethod( ). To access the static method you
write:
Button.SomeMethod( );
rather than writing:
btnUpdate.SomeMethod( );
In C# it is not legal to access a static method or member variable through an instance, and trying to do so will generate a compiler error (C++ programmers, take note).
Some languages distinguish between class methods and other (global) methods that are available outside the context of any class. In C# there are no global methods, only class methods, but you can achieve an analogous result by defining static methods within your class.
Static methods act more or less like global methods, in that you can invoke them without actually having an instance of the object at hand. The advantage of static methods over global, however, is that the name is scoped to the class in which it occurs, and thus you do not clutter up the global namespace with myriad function names. This can help manage highly complex programs, and the name of the class acts very much like a namespace for the static ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access