Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitted setter vs private setter?

Tags:

c#

c#-6.0

What is the difference between a property with a omitted setter and a property with a private setter?

public string Foo { get; private set; } 

vs

public string Foo { get; } 
like image 622
Fred Avatar asked Apr 22 '16 11:04

Fred


People also ask

What is a private set?

Private set intersection is a secure multiparty computation cryptographic technique that allows two parties holding sets to compare encrypted versions of these sets in order to compute the intersection. In this scenario, neither party reveals anything to the counterparty except for the elements in the intersection.

What is the use of private set?

Use private set when you want setter can't be accessed from outside. Use readonly when you want to set the property only once. In the constructor or variable initializer.

What does private set mean in Swift?

Using only private(set) means that the getter is internal - so not accessible outside the module.

What does get private set mean in C#?

Since it is a read operation on a field, a getter must always return the result. A public getter means that the property is readable by everyone. While the private getter implies that the property can only be read by class and hence is a write-only property.


2 Answers

In C# 6, get; only properties are only settable from the constructor. From everywhere else, it is read-only.

A property with a private set; can be set from everywhere inside that class.

like image 51
Patrick Hofman Avatar answered Sep 29 '22 08:09

Patrick Hofman


From outside the class, it won't change anything if you use this syntax:

public string Foo { get; } 

But you won't be able to update Foo within the class, except in the constructor, to do so, you'll need the private setter:

public string Foo { get; private set; } 
like image 36
Thomas Ayoub Avatar answered Sep 29 '22 07:09

Thomas Ayoub