What is the difference between {get; set;}, {get; private set;} and {get;}?

Viewed 2530

I am new to C#, but I have used {get; set;} and found this {get; private set} and this {get;} in some earlier set of code written by someone else.

What does this exactly mean? What is the difference between {get; set;} and {get; private set;} and {get;}?

1 Answers

When you write

public int MyProperty {get; set;}

both getter an setter have accessibility of MyProperty, which is public in this case. When you write

public int MyProperty {get; private set;}

only the getter remains public, while the setter becomes private. This approach is used to make properties that can be written only from inside of the class.

New version of C# gives you a closely related construct

public int MyProperty {get;}

which lets you make your property read-only. This is similar to {get;private set;} but in addition it restricts all assignments of MyProperty to the constructor of its containing class.

Related