jax
jax

Reputation: 747

Private members in .net?

If there are properties, is there any use of private variables? Also, is there any such thing as a private property?

The question came up as I working with a program today. I realized that having to declare all my properties as public. I then realized I didn't have much private members anymore. Excuse me this question is stupid, I come from a pure C++ background.

Upvotes: 1

Views: 34

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149000

Yes and yes. Most properties, including public ones are back by private fields. This is necessary because properties are just getter and/or setter methods, and you still need a physical location to store them.

For example, an auto-implemented property like this:

public int MyValue { get; set; }

Compiles to something like:

private int _myValue;

public int MyValue { 
    get { return this._myValue; }
    set { this._myValue = value; }
}

Notice that the property still requires an actual field to store its value.

Now about private properties, yes this is still useful. The most common case is when you want to encapsulate some simple logic, but don't want to do it in a method. For example:

private MyObject _myObject;

private MyObject MyObject { 
    get { 
        if (this._myObject == null)
            this._myObject = new MyObject();
        return this._myObject;
    }
}

Now, elsewhere in your code you can simply refer to this.MyObject without having to do the null check every time.

It's also useful in certain situations involving serialization, or anywhere else where something may be reflecting over the private members of your type. In these cases it's useful to have an actual property, even if it's never exposed publicly.

Upvotes: 2

Related Questions