Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a property with a private setter and a property with no setter?

If I want a read-only property, I write it like:

public int MyProperty { get { //Code goes here } }

However, the Microsoft example (and a few other examples I've seen) are written like:

public int MyProperty { get; private set; }

Is there any difference between these two, and should I start writing properties like this?

like image 283
svbnet Avatar asked Nov 30 '22 12:11

svbnet


2 Answers

As you can see in your second sample, you can leave out the implementation for a property. .NET will then automatically create a local variable for the property and implement simple getting and setting.

public int MyProperty { get; private set; }

is actually equivalent to

private int _myProperty;

public int MyProperty { 
    get { return _myProperty; }
    private set { _myProperty = value; }
}

Writing

public int MyProperty { get; }

does not work at all, as automatic properties need to implement a getter and a setter, while

public int MyProperty { get; private set; }

leaves you with a property that may return any int, but can only be changed within the current class.

public int MyProperty { get { ... } }

creates a read-only property.

Question is: what do you need? If you already have a member variable that's used within your class and you only want to return the current value using a property, you're perfectly fine with

public int MyProperty { get { return ...; }}

However, if you want a read-only property, which you need to set within your code (but not from other classes) without explicitly declaring a member variable, you have to go with the private set approach.

like image 148
Thorsten Dittmar Avatar answered Dec 06 '22 04:12

Thorsten Dittmar


With private setter you can only assign property value inside of instance when property is without setter you can't set its value anywhere.

like image 37
gzaxx Avatar answered Dec 06 '22 04:12

gzaxx