Question

Reading C# Step by Step, the author mentiones the class is just blueprint for objects and itself is useless. Well, how then comes static classes can work alone?

I do understand the concept that static classes cannot be instantiated and exist as one unique instance with its static members. But that ruins, a bit, the metaphor of classes as blueprints. How could static classes be explained in relation to this blueprint idea?

Was it helpful?

Solution

No, a static class doesn't exist as one unique instance. There are no instances of a static class. There are just static members, which are associated with the type itself, rather than any instance.

Once you get the idea of static meaning "related to the class, not an instance" it makes sense, IMO. It's hard to come up with particularly real-world analogies along the "blueprint" lines though.

It's worth noting that the concept of static methods is exactly same for "normal" classes as for static classes: even with a normal class, you can call a static method without ever creating an instance of the class.

OTHER TIPS

Joel Spolsky once blogged about The Law of Leaky Abstraction, I'm going to proclaim "The Law of Leaky Analogy".

All analogy breaks, while it's fine to think of a class as a blueprint, don't get too hung up when you see things that just doesn't fit that analogy. In any case, that class have static members is reality; that the blueprint analogy cannot accommodate static members, is because the analogy is not the reality.

In the end, it all comes up to what's convenient for the programmer; if it's convenient to use a method that isn't attached to a particular instance of an object, then use static methods. A language feature exists to make the programmer's life easy, not to fulfill the analogy.

You example is one where a static class makes no sense. However if there is only ever going to be one blueprint in the system ever then you can argue that a static class is ok.

A static class can be viewed as a repository of methods that do not need an instance. It acts as a kind of service provider for your classes.

The extension methods are all defined in static classes for example.

As mentioned in Head First C# book, The word "Static" isn't really all that intuitive, many people do get confused about the meaning and terminology.

"If you think of a class as a blueprint used to create objects, then you can think of static fields and methods are being part of the blueprint itself." At the time, class as cookie cutter was the analogy for teaching OOP. I thought class as blueprint was a big improvement :)

Regards, Jeff (JAL)

P.S. Hi John S.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top