Static Classes in C# 2.0

In C# 1.0 if you wanted to ensure that no outside user can create an instance of class and that class user should use static method or properties to use the class,  you would normally mark the class as sealed and make the constructor private. When you make the constructor private, no outside user can create an instance of the class. Marking the class as sealed prevents any outside user to extend the behavior of the class. However the draw back to this approach is having two change two things and secondly you can get away with declaring instance level properties or method without compiler raising an error. Obviously those methods and properties are pretty much useless since no one can create an instance of the class. Here is how you would create the class in C# 1.0.

image

In the above code, you will notice that when I try to create an instance of CustomerRepository, compiler raises an error because the constructor is marked private. However I can still get away with declaring instance level properties and methods. With C# 2.0, static keyword was introduced which does all the magic of making the constructor private and sealing the class as well. It also goes one step ahead and ensures that you can only declare static methods and properties. Creating instance level methods and properties causes the compilation errors. Here is how the static class looks like.

image

No Comments