Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically generated property {get; set;} vs {get; private or protected set;} in C#

Tags:

c#

properties

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);
    }
...
}
like image 910
prosseek Avatar asked Sep 24 '11 01:09

prosseek


2 Answers

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.

like image 64
BoltClock Avatar answered Oct 05 '22 07:10

BoltClock


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.

like image 33
Shan Plourde Avatar answered Oct 05 '22 07:10

Shan Plourde