Note that there are some explanatory texts on larger screens.

plurals
  1. POImmutable read-only objects vs object with automatic properties
    primarykey
    data
    text
    <p>I've been wondering about this for a while and haven't been able to find much commentary on the subject and haven't been able to come on a conclusion by myself.</p> <p>When creating objects, it's accepted best practice to make the object as limited as possible in terms of exposing data and allowing that data to manipulated. If you can make an object immutable, especially in multi-threaded applications, then it is best to do so.</p> <p>Having said that, C# seems to favor the developer who doesn't follow this rule by allowing the definition of a class to be much more simple, and more importantly, easier to maintain.</p> <p>Take the following read-only immutable class:</p> <pre><code>public class ActiveDirectoryUser { private readonly string firstName, lastName, office, username, email; public ActiveDirectoryUser(string firstName, string lastName, string office, string username, string email) { this.firstName = firstName; this.lastName = lastName; this.office = office; this.username = username; this.email = email; } public string FirstName { get { return firstName; } } public string LastName { get { return lastName; } } ... public string Email { get { return email; } } } </code></pre> <p>And compare it to the much more simple example as below, which isn't read-only.</p> <pre><code>public class ActiveDirectoryUser { public string FirstName { get; set; } public string LastName { get; set; } ... public string Email { get; set; } } </code></pre> <p>Which can be instantiated with the following is:</p> <pre><code>ActiveDirectoryUser user = new ActiveDirectoryUser { FirstName= "Sam", LastName = "Shiles", ..., Email ="Sam@shiles.com" }; </code></pre> <p>Given the simpler definition, the fewer lines of code, the less chance for developer error and the ease with which another developer can understand the code (especially with examples that are more true to life than our simple example), is the value of creating proper read-only, immutable objects, worth the cost? </p> <p>Also, do other people believe that making immutable objects in C# should be made easier with an automatic-esq syntax such as:</p> <pre><code>public string FirstName {get; readonly set;} </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload