This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Static Behaviour

The fifth article in the C# Object-Oriented Programming tutorial describes the use of static methods, properties and constructors. These behaviours are accessible from classes without the requirement to instantiate new objects.

Using a Static Property

To use the static property, the property name is preceded by the class name and the member access operator (.). To demonstrate, adjust the Main method to perform two mass calculations and output the call count property as follows:

static void Main(string[] args)
    int density = 50;
    int volume = 100;
    int volume2 = 180;

    int mass1 = MassCalculator.CalculateMass(density, volume);
    int mass2 = MassCalculator.CalculateMass(density, volume2);
    int calls = MassCalculator.CallCount;

    Console.WriteLine("Mass1: {0}", mass1);         // Outputs "Mass1: 5000"
    Console.WriteLine("Mass2: {0}", mass2);         // Outputs "Mass2: 9000"
    Console.WriteLine("Calls: {0}", calls);         // Outputs "Calls: 2"

Static Constructors

A static constructor is used to initialise the static state of a class when it is first used. This is similar to a standard constructor with some exceptions. A static constructor is always declared as private and as such may not be directly called by a program. A static constructor therefore has no facility to add parameters. It is also not possible to include a static destructor.

To add a static constructor, create a private constructor with the static keyword as a prefix. the following code could be added to the MassCalculator class if the appropriate static methods were available to retrieve the previously saved call count from a file or other storage.

static MassCalculator()
    _callCount = InitialiseCallCount();
14 October 2007