Tested with Microsoft Visual C# 2005 Beta 1, .Net 2.0.40607.42
Well, while not as exciting as many of the other new features of C# 2.0, static classes give us a faster way
of implementing classes who's only purpose is to deliver static members. While you can always just create a
class with a private constructor, so that it doesn't get instantiated, and then add all static members,
static classes enforce those requirements automatically. Static classes are sealed (they can't be derived from),
they can't be instantiated (made an instance object from) and they can't contain a constructor.
namespace WhatsNew20StaticClasses
{
class Program
{
static void Main(string[] args)
{
MyStaticClass.PrintMessage("Hello World!");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
public static class MyStaticClass
{
public static void PrintMessage(String Message)
{
Console.WriteLine(Message);
}
}
}
Why at all have Static "Classes" when classes were made to be a blue print of objects that are to be instantiated logicallyBy Michael G. @ 7/13/2005 11:13:56 AM
The main reason would be: improved performance. Static access means that the instantiation of an object is unncessary. The .Net framework maintains a single object in memory for static members. A static class is more of a rule: it means that you can't instantiate it as an object and that it can only have static members. I use static members whenever possible and only use instantiated class objects whenever more than copy of the object will be necessary to carry the intended function of the project.By DaveW @ 3/19/2006 5:32:40 PM
Mike,
Static classes can contain constuctrors. You can't specify their protection, and there can be only. Just like highlander.