What difference does this "private set" make in this immutable class
I am studying this simple class and wondering what is the real difference in private set
name property
?
If this line just reads public string Name { get; }
, how would the user interaction with the class change?
public class Contact2
{
// Read-only properties.
public string Name { get; private set; }
public string Address { get; }
// Private constructor.
private Contact2(string contactName, string contactAddress)
{
Name = contactName;
Address = contactAddress;
}
// Public factory method.
public static Contact2 CreateContact(string name, string address)
{
return new Contact2(name, address);
}
}
They are read-only properties, and objects of this class can only be created using a static method, so what does it matter if the set
name is private or not?
EDIT
This is part of this MSDN code:
https://msdn.microsoft.com/en-us/library/bb383979.aspx
source to share
In C # 6:
public string Name { get; private set; }
Can be set from any method within the class.
public string Address { get; }
This property is read-only and can (and should) only be set on initialization.
They work the same in your code, but the read-only property enforces an additional constraint that makes the property immutable because it can only be set once, whereas you can add a method to the class that mutates to Name
make the class mutable.
source to share