I am new to C# and I came across the following query. Since a class is not an object but just a blueprint(template), how is it possible to define static members on the class and access them by using the class name? This does not make sense to me. My understanding is class does not exist as an entity, so where static properties live? Where am I wrong?
1 Answer
Statics are statics. In this scenario, the class acts more like a namespace. It's not that the statics exist on the class, but rather simply accessed through the class.
2 Comments
MakePeaceGreatAgain
Actually
static variables exist only on the class, however not on an instance of it.Chris Pratt
@HimBromBeere: If by that you mean that they can only be accessed through the class, not an instance of the class, then you are correct, but I also never claimed differently. They do not, in fact exist on the class though. As the OP rightly ascertained, the class is not an actual entity. It's not present in memory, etc., so it's not actually accurate to say the statics exist on the class, since the class itself doesn't "exist".
static-keyword on MSDN? Clearly points out how and when to use it. In your meaning: everythingstaticjumps out of the template, as it´s statically bound to the class.staticmembers of the class.staticclass variable is not associated to any single instance of that class, but exists anyway even if no instance of the class is created by your program. You can consider it as a global variable, but with a class scope, meaning you have to access it qualifying with the class name and following the visibility rules (public, private, etc)