Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hey guys

I know that when an object is static only one of that object can exist at any given time. I also know that if a class is static I don't need to instantiate it to use it which is very useful :)

What i don't get is why is it useful to have a static variable inside of an instantiate-able class?

Example:
public class Foo
{
    public Foo(int Bar)
    {
        bar = Bar;
    }

    private static int bar;
    public static int Bar
    {
        get { return bar; }
        set { bar = value; }
    }
}


Thanks
Posted

Generally, if you want multiple objects of the same type to share data. For example, you might have a static RootNode member, if all your objects need to refer to it - that way you only need to initialise it once for the whole class, rather than per-instance
 
Share this answer
 
Every info that has to be shared by all the instances (or none of them) of the class could be a good candidate.
For instance if you want to count how many instances (pardon the pun) of the class were created.
:)
 
Share this answer
 
v2
Another example is a Message class in which each instance has a unique ID that is the previously assigned ID + 1;
 
Share this answer
 
Thread safety can make heavy use of a static variable. If you are aiming to lock a section, it makes sense for the variable to be static so that you achieve the aim of locking based on one object. For instance:
private static readonly object _syncLock = new object();

public void CriticalProcess()
{
  lock(_syncObject)
  {
    // Do something critical here.
  }
}
 
Share this answer
 
wrote:
What i don't get is why is it useful to have a static variable inside of an instantiate-able class?


Think about string.Empty. Empty is a public static field on class System.String. It is often used when you implement singleton design pattern.
 
Share this answer
 
wrote:
why is it useful


IMO, its not (unless you want a counter of some sort).
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900