I am new to C#, but I have used {get; set;}
and found this {get; private set}
in some earlier set of code written by someone else.
What does this exactly mean? And what is the difference between
{ get; set; }
and { get; private set; }
?
Join Stack Overflow to learn, share knowledge, and build your career.
I am new to C#, but I have used {get; set;}
and found this {get; private set}
in some earlier set of code written by someone else.
What does this exactly mean? And what is the difference between
{ get; set; }
and { get; private set; }
?
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.
{get;}
, that's what I actually came here for. Your answer perfectly explains that, too.
– Cornelius Roemer
Nov 29 '20 at 17:20