0

I have been having a hard time deciding when I should declare a class filed as static. I got the idea that a static field is shared among all objects created from a class, unlike a regular non-static field, which is held by each of the objects.

Then if it is known that only one object will be created from a class (because I have seen such cases many times), what is the meaning of a static field? If the definition of "static" is "shared among all instances," does a static field serve the same role as a regular non-static field, provided there is only one object created from the class?

I got this old project from my boss to study C#, and I see some fields declared as static in a class, but there is only one object created from the class, and I am a bit confused what the point is if it does not have multiple instances.

jun
  • 55
  • 1
  • 10
  • Nothing changes. The class doesn't know that the developer intends to only create a single instance. If you know that you have a singleton class though, there is no reason to use a static field – Panagiotis Kanavos Jun 02 '17 at 14:09

1 Answers1

0

You should not decide to use static just because there´s only one single instance. As you´ve already mentioned there is an instance.

The question if something should be static depends on if your member depends on an internal state, that is do you need to set some property befpore you can incoporate with this member. So even if there´s just one single instance existing this instance shares a set of members defining its state. Only when your member could omit all those information from that single instance it should be marked static.

However making some member static makes many things - e.g. mocking - quite hard as you create a heavy dependency on your class holding that member

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111