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.
Note
VB6
programmers
take
note: Don’t confuse the
static keyword in C# with the
Static keyword in VB6 and VB.NET. In Visual Basic,
the Static keyword declares a variable that is
only available to the method it was declared in. In other words, the
Static variable is not shared among different
objects of its class (i.e., each Static variable instance has its own value). However, this variable exists for the life of the program, which allows its ...
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