0

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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Unknown developer
  • 5,414
  • 13
  • 52
  • 100
  • 3
    Did you read the `static`-keyword on [MSDN](https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members)? Clearly points out how and when to use it. In your meaning: everything `static` jumps out of the template, as it´s statically bound to the class. – MakePeaceGreatAgain Jan 29 '18 at 15:05
  • 1
    Simple: a class *does* exist as an entity. That it's not an object in the language sense doesn't mean it can't have properties, unless your notion of a property is hardwired to objects. The idea of a class as "only a blueprint" is fine in theory, but not quite how things are actually implemented. If you want, pretend every class also has a single object associated with it that's automatically instantiated and only contains the `static` members of the class. – Jeroen Mostert Jan 29 '18 at 15:08
  • 1
    The class clearly does exist as an entity. Static properties exist on the class. –  Jan 29 '18 at 15:08
  • a `static` class 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) – Gian Paolo Jan 29 '18 at 15:12
  • 1
    Sounds like a philosophical question and not a technical one. Some people will say class exists as entity, some will say it does not. But it doesn't change how static members of class work. – Evk Jan 29 '18 at 15:14

1 Answers1

1

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.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Actually `static` variables exist *only* on the class, however not on an instance of it. – MakePeaceGreatAgain Jan 29 '18 at 15:07
  • 1
    @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". – Chris Pratt Jan 29 '18 at 15:11