Static and instance methods
A method declared with a static modifier is a static method. A static method does not operate on a specific instance and can only directly access static members. A method declared without a static modifier is an instance method. An instance method operates on a specific instance and can access both static and instance members. The instance on which an instance method was invoked can be explicitly accessed as this. It is an error to refer to this in a static method. The following Entity class has both static and instance members. class Entity int serialNo; public Entity() { public int GetSerialNo() { public static int GetNextSerialNo() { public static void SetNextSerialNo(int value) { Each Entity instance contains a serial number (and presumably some other information that is not shown here). The Entity constructor (which is like an instance method) initializes the new instance with the next available serial number. Because the constructor is an instance member, it is permitted to access both the serialNo instance field and the nextSerialNo static field. The GetNextSerialNo and SetNextSerialNo static methods can access the nextSerialNo static field, but it would be an error for them to directly access the serialNo instance field. The following example shows the use of the Entity class. using System; class Test Entity e1 = new Entity(); Console.WriteLine(e1.GetSerialNo()); // Outputs "1000" Note that the SetNextSerialNo and GetNextSerialNo static methods are invoked on the class whereas the GetSerialNo instance method is invoked on instances of the class.
|