I see a lot of code uses automatically generated property like {get; private set;} or {get; protected set;}.
What’s the advantage of this private or protected set?
I tried this code, but it’s the same when I have Foo{get; set;}.
public class MyClass
{
public int Foo {get; private set;}
public static void RunSnippet()
{
var x = new MyClass();
x.Foo = 30;
Console.WriteLine(x.Foo);
}
...
}
It makes a property read-only by external sources (i.e. classes that aren’t
MyClassand/or its subclasses). Or if you declared the propertyprotectedwith aprivate set, it’s read-only by its subclasses but writable by itself.It doesn’t make a difference in your class because your setter is private to that class, so your class can still access it. However if you tried to instantiate
MyClassfrom another class, you wouldn’t be able to modify theFooproperty’s value if it had a private or protected setter.privateandprotectedmean the same here as they do elsewhere:privaterestricts access only to that very class, whileprotectedrestricts access to that class and all its derived classes.