Static and Instance Members
The fields, properties, and methods of a class can be either instance members or static members. Instance members are associated with instances of a type, whereas static members are associated with the class itself, and not with any particular instance. All methods are instance methods unless you explicitly mark them with the keyword static
.
The vast majority of methods will be instance methods. The semantics of an instance method are that you are taking an action on a specific object. From time to time, however, it is convenient to be able to invoke a method without having an instance of the class, and for that, you will use a static method.
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 that the Button
class has an instance method Draw( )
and a static method GetButtonCount( )
. The job of Draw( )
is to draw the current button, and the job of GetButtonCount( )
is to return the number of buttons currently visible on the form. Since GetButtonCount( )
applies to more than just the one button, it wouldn’t make sense to call it on a specific instance of Button
; therefore, it’s static.
You access an instance method through an instance of the class—that is, through an object:
btnUpdate.SomeMethod( );
You access a static method through the class name, not through an instance:
Button.GetButtonCount( ); ...
Get Learning C# 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.