C# 2.0: life was a bit more difficult without Static classes
Usefulness of a new feature is best understood if you try to implement something that the feature targets without using that feature. I started programming in C# when v2.0 was already available internally, so I got used to many of the new features in v2.0 without realizing the people outside have to work hard to get the same thing done.... One of these features is static classes. We use this in lot of places in our Team System code to group resources like constant strings, methods that operate on them and also utility methods that do not need any instance to operate. So a typical implementation is something like
public static class BuildStatus{ public static string Initializing { get { return BTRes.Initializing; } } public static string Sync { get { return BTRes.sync; } } public static string SyncCompleted { get { return BTRes.syncCompleted; } } /* ... */ internal static bool IsOneOfCompletedStatus(BuildStatusIconID status) { /* ... */ }}
Marking these classes as static ensure all of the following
- Ensure that only static members can be placed in them
- Unnecessary instance of the class will not be created
- They are sealed and cannot be inherited from
- They will not contain instance constructors
Pre C#2.0 classes couldn't be marked as static and the workaround was to use the following pattern
public sealed class MyStaticClass{ private MyStaticClass(){} public static void MyStaticMethod(){ /* ... */} public static string Author = "Abhinaba";}
So the class had to be marked sealed to stop inheriting and you needed to have a private constructor to stop creation of instances. Even then things did not work out perfectly as anyone could just go ahead and add instance members. With static modifier being supported for classes, the compiler can ensure that no instance members are added by mistake and it also helps in code-readability.
Comments
- Anonymous
December 01, 2005
interesting article - Anonymous
December 01, 2005
Nice article... I wasn't really even aware of static classes in C# 2.0, even though obviously I had been using them (static class Program).