X hits on this document





30 / 396

Chapter ‎18   Unsafe code

public int GetSerialNo() { return serialNo; }

public static int GetNextSerialNo() { return nextSerialNo; }

public static void SetNextSerialNo(int value) { nextSerialNo = 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 access the serialNo instance field.

The following example shows the use of the Entity class.

using System;

class Test { static void Main() { Entity.SetNextSerialNo(1000);

Entity e1 = new Entity(); Entity e2 = new Entity();

Console.WriteLine(e1.GetSerialNo());// Outputs "1000" Console.WriteLine(e2.GetSerialNo());// Outputs "1001" Console.WriteLine(Entity.GetNextSerialNo());// Outputs "1002" } }

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. Virtual, override, and abstract methods

When an instance method declaration includes a virtual modifier, the method is said to be a virtual method. When no virtual modifier is present, the method is said to be a non-virtual method.

When a virtual method is invoked, the runtime type of the instance for which that invocation takes place determines the actual method implementation to invoke. In a nonvirtual method invocation, the compile-time type of the instance is the determining factor.

A virtual method can be overridden in a derived class. When an instance method declaration includes an override modifier, the method overrides an inherited virtual method with the same signature. Whereas a virtual method declaration introduces a new method, an override method declaration specializes an existing inherited virtual method by providing a new implementation of that method.

An abstract method is a virtual method with no implementation. An abstract method is declared with the abstract modifier and is permitted only in a class that is also declared abstract. An abstract method must be overridden in every non-abstract derived class.

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.17

Document info
Document views1278
Page views1278
Page last viewedFri Jan 20 15:03:49 UTC 2017