✅ Can someone help improve my understanding of the use of static?
I understand that static is used for things like objects within a class, but what does it actually do?
7 Replies
after doing a bit more research I think that static sort of includes all objects within the constructors of a class, if this is correct does static have any other uses?
A normal field is specific to a particular instance of an object:
A static field is common to all instances of an object:
oh that makes a lot more sense thank you.
Likewise a
static method is called on the class itself:
You can't access any instance fields or instance methods from a static method
And a static class is just a helpful thing, and means that compiler stops you from putting any instance fields or instance methods in that class
An instance constructor is run when you do new A(). A static constructor (static A() { ... }) is run at some point before the first instance is created or any static fields are accessed, and you can use it to initialise static fields
I think that's everything... All clear?In languages like C#, non-static classes without any static members are like instructions for how to create something that potentially has some state, some behavior, or both.
So, if you define a
class called Dog with an instance method called Bark() and a field called name, the class Dog doesn't itself have a name or know how to bark, but it is the definition of how to create such a Dog. You create a dog by instantiating an instance of the Dog class via var myDog = new Dog("Fido"). Now that instance stored in myDog has some name (probably "Fido" given the constructor example), and it knows how to bark via myDog.Bark(); So now myDog has a name and knows how to bark, and you can make many more instances of Dog that have their own, not-shared names and all know how to bark, but the class Dog itself does not - it only defines what instances of Dog can do.
When you declare a member as static, you're saying that that member belongs to the type itself, not any instance of the type. If you add a static method to your Dog class like static Dog[] GetAllKnownDogs() {...}, now the type Dog itself knows how to tell you how to get all known instances of the Dog class. You would call that method like Dog.GetAllKnownDogs() - you would not need to first create an instance of the Dog class like myDog.
So to summarize, static members belong to the type itself, and non-static members belong to any instances you create of that type, whether it's a class or a struct.
There are more details involving object lifetimes around static members, like you can make things static per thread, or you can have different app domains or processes that have their own instances of static fields, but you're unlikely to run into those things if you're just starting to learn.$close
If you have no further questions, please use /close to mark the forum thread as answered