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), but they can contain constructors.
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.
Regards,
DaveBy Dinesh Mandal @ 7/13/2006 5:54:02 AM
What does this mean - " A static class can have constructor."?
What is the purpose of a constructor in a static class?
Please, make me clear.
All classes can have a class (static/shared) constructor. The class constructor is called just before the first time any instance method or any class method is called.
You can in C# do this.
public class Singleton
{
private static Singleton _instance;
static Singleton()
{
_instance = new Singleton();
}
...
}
Which is also a thread safe way of implementing a singleton, because the class constructors are thread safe in .NET.By mudiqgnn @ 2/27/2007 11:23:23 PM