C# Static Behaviour

Why Use Static Behavior?
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 behavior 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 behavior. 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’ 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 behavior. We can now add the read-only call count property to the class.

public static int CallCount
{
get
{
return _callCount;
}
}

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 initialize 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();
}

Tagged , . Bookmark the permalink.

Leave a Reply