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 MyClass
and/or its subclasses). Or if you declared the property protected
with a private 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 MyClass
from another class, you wouldn't be able to modify the Foo
property's value if it had a private or protected setter.
private
and protected
mean the same here as they do elsewhere: private
restricts access only to that very class, while protected
restricts access to that class and all its derived classes.
It makes a difference when you have a class model that uses inheritance. If your MyClass methods are clients of your private fields and methods it makes no difference.
That said, even if you don't anticipate your MyClass becoming a parent class in any sort of class hierarchy, it doesn't hurt to limit your field and method scope to the least visible scope that it requires. Encapsulate what you can with the least visible scope by default so that you don't have to refactor when subclasses start to access parent properties that they shouldn't be. The level of effort isn't any different from not doing so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With