One example involves the Main method. The Common Language Runtime (CLR) needs to have a common entry point to your application. So that the CLR doesn't have to instantiate one of your objects, the rule is to define a static method called Main in one of your classes. You'd also want to use static members when you have a method that, from an object-oriented perspective, belongs to a class in terms of semantics but doesn't need an actual object-for example, if you want to keep track of how many instances of a given object are created during the lifetime of an application. Because static members live across object instances, the following would work: -
using System; class InstCount { public InstCount() { instanceCount++; } static public int instanceCount = 0; } class AppClass { public static void Main() { Console.WriteLine(InstCount.instanceCount); InstCount ic1 = new InstCount(); Console.WriteLine(InstCount.instanceCount); InstCount ic2 = new InstCount(); Console.WriteLine(InstCount.instanceCount); } }
In this example, the output would be as follows: -
0 1 2
A last note on static members: a static member must have a valid value. You can specify this value when you define the member, as follows: -
static public int instanceCount1 = 10;
If you do not initialize the variable, the CLR will do so upon application startup by using a default value of 0. Therefore, the following two lines are equivalent: -
static public int instanceCount2; static public int instanceCount2 = 0;