BlackWaspTM

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.

Why Use Static Behaviour?

To date, the methods, properties and constructors that have been described in this tutorial have all related to instantiated objects of classes. In each case, these members have defined how the individual objects behave and how they maintain and manipulate their own state. Sometimes you will want to create behaviour that is not linked to any individual object, instead being available to all instances and to objects of other classes. This is where static members become useful.

A good example of a static method is the Main method, which is used in every executable program. When a program is launched, no instances of any class are present in memory. As the Main method is static, it can be called without creating an object and can then assume control of the program. It is the Main method's task to create the objects that the program requires to function correctly.

In this article, we will create a new utility class that performs a simple scientific calculation. This class provides a method that accepts the density and the volume of an item and calculates its mass. The class will also maintain a property that counts the number of times that the calculation has been performed. To begin, create a new console application and add a new class named 'MassCalculator'.

Static Methods

Static methods are useful when creating functions that are not reliant on any instance of a class. An example of the extensive use of static members is the Math class, which is a library of mathematical functions and constants provided by the .NET framework.

Creating a Static Method

A static method is declared using a similar syntax to a class method. The 'static' keyword is used in the declaration to indicate the modified behaviour. To add the mass calculation method to the new class, insert the following code:

public static int CalculateMass(int density, int volume)
{
    return density * volume;
}

Calling a Static Method

Static methods are called without reference to a specific instance of a class. Instead of supplying an object name followed by the method name, the class name and method name are used, separated by a full stop (or period). We can demonstrate this using the Main method of the console application as follows:

static void Main(string[] args)
{
    int density = 50;
    int volume = 100;
    int mass = MassCalculator.CalculateMass(density, volume);

    Console.WriteLine("Mass: {0}", mass);           // Outputs "Mass: 5000"
}

It is important to understand that static methods may not directly use non-static members. It is invalid for one static method to directly call a non-static method or property without first instantiating an object. Similarly, private variables that are not marked as static cannot be utilised by a static method. The reverse of this is not true of course, as a non-static member can call a static method.

Static Properties

Static properties provide the functionality of standard properties, except that the property is not linked to any instance of the class. Properties can be read/write, read-only or write-only as with standard properties. As such, they can essentially be thought of as global variables.

Creating a Static Private Variable

In the earlier article describing class properties we created a class-level private variable to hold the data behind a property. As mentioned above, private variables may not be accessed by static methods, and this also applies in the case of static properties. Instead, we must create a static private variable if the property value is to be held rather than calculated.

In the MassCalculator class we will implement a call counter that is incremented every time the mass calculation method is used. The current value for the call counter is stored in a static private variable that may now be added within the class's code block:

private static int _callCount;

To maintain the counter, adjust the CalculateMass method so that it increments the variable on every call:

public static int CalculateMass(int density, int volume)
{
    _callCount++;
    return density * volume;
}

Exposing a Static Property

As you may expect, adding a static property to a class requires only that the declaration includes the 'static' keyword to modify the property's behaviour. We can now add the read-only call count property to the class.

public static int CallCount
{
    get
    {
        return _callCount;
    }
}
14 October 2007