Sossenbinder
Sossenbinder

Reputation: 5302

I need some help understanding the use of a private static variable

I already read up on a few posts here about private static, and I think I somehow got the idea, but I still have to ask for some help on clearing me up on this one.

Currently I am going through a class I didn't write, and I found this at the beginning private static string x.

I never came across private static, only public static for constants or similar things.

So now towards my question: What advantage does private static have?

I'm not sure if I'm correct, but as far as I understood, it's allowing the variable to only be accessible by methods of this class due to private. The static part however tells me that that variable is unique and bound to the class, rather than to its objects, so assuming we have 5 instances of the class containing private static string x, all 5 instances will always have the same value when evaluating x.

Is this correct?

Upvotes: 0

Views: 335

Answers (2)

Sylwekqaz
Sylwekqaz

Reputation: 329

private static its useful for encapsulation of variables

for example java like enum

class MyEnum
{
    private static List<MyEnum> _values;
    public static Enumerable<MyEnum> Values {get { return _values.ToArray()}} 

    public static readonly FOO = new MyEnum('foo');
    public static readonly BAR = new MyEnum('bar')

    private MyEnum(string s)
    {
      //...
      _values.Add(this);
    }
}

as you can see we have _values variable which is not accessible from other class. But other class can obtain read-only copy via Values.

Upvotes: 0

i486
i486

Reputation: 6563

Yes. It is "global" variable for all objects of this class.

Upvotes: 2

Related Questions