Wednesday, November 19, 2008

Uses of the Static Keyword in C#.NET (Static Classes)

When a class has been defined as static, it is not creatable using the new keyword, and it can contain only static members or fields (if this is not the case, you receive compiler errors). Static classes are sealed class by default that means a static class cannot be inherited by other class.

This might seem like a very useless feature, given that a class that cannot be created and cannot be inherited does not appear all that helpful. However, if you create a class that contains nothing but static members and/or constant data, the class has no need to be allocated in the first place. Consider the following type:

static class UtilityClass
{
public static void PrintTime()
{ Console.WriteLine(DateTime.Now.ToShortTimeString()); }

public static void PrintDate()
{ Console.WriteLine(DateTime.Today.ToShortDateString()); }
}

Given the static modifier, object users cannot create an instance of UtilityClass:

static void Main(string[] args)   
{
UtilityClass.PrintDate();
// Compiler error! Can't create static classes.
UtilityClass u = new UtilityClass();
//...
}

No comments: