I have two questions about static + const members and static classes.
One: Why would you declare a class that has all static and const members and not make the class static?
I have been studying .net code in reflector as a learning exercise. The class I have been studying that demonstrates this design is the FormsAuthentication class. All of it’s members are marked static or const yet the class it’s self is marked public sealed The only non static member in the class is a default constructor with no implementation. Why has this class not been marked public static sealed?
My second question is regarding why the members in the FormsAuthentication class are declared as static. As I understand it there could be many HttpApplications running in the app’s AppDomain and all these HttpApplications would share the same FormsAuthentication classes’ static members.
Two: Doesn’t this cause a bottleneck? If so why is it designed like this?
The reason is that FormsAuthentication is a class that predates the static class feature. It was introduced in .Net 1.1, which didn’t have the concept of static classes. Since the class is working, and there’s no benefit to changing it now, its likely no one is going to revisit it to remove the private ctor and make it static instead of sealed.
Its likely static as the auth can be thought of as a singleton. You’d not need more than one instance of FormsAuthentication in your application (though technically with a static class there is never an instance, but with FormsAuth there potentially can be one, you’d have to decompile to see). Since there’s no need to create more than one instance, static methods suffice. It does make unit testing code that relies on it more difficult, but at the time there wasn’t as much consideration given to unit testing. You can’t pass instances of static classes to methods, whereas with singletons you can.
The only bottleneck is that there is likely locking behind the scenes, as .Net typically provides thread safety for static members. Realistically though this is unlikely to cause problems; it may have thread local storage as well, so it may not do any locking at all. You’d have to decompile it to be sure.
It depends on whether or not there’s static data that must be locked to ensure thread safety. If there is, locking can cause some contention for a shared resouce as threads will wait for the critical section to unlock and even then only one thread will be allowed in, others will wait their turn. But you can also have static methods which ONLY use information from parameters or thread local storage variables, in which case there’s no syncronization issues involved, and the methods can be called independantly with no bottle neck.