Created
July 12, 2020 06:54
-
-
Save way2datta/4174d4e7378bc31eeeb532995f56228c to your computer and use it in GitHub Desktop.
Protect Your Immutable Object Invariants
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Student | |
{ | |
public readonly string Name; | |
public readonly string Email; | |
public readonly List<String> Subjects; | |
public Student(string name, string email, List<String> subjects) | |
{ | |
this.Name = name; | |
this.Email = email; | |
this.Subjects = subjects; | |
} | |
public override string ToString() | |
{ | |
return ToDisplayString(); | |
} | |
public string ToDisplayString() | |
{ | |
return $"Name: {Name}, Email: {Email}, Subjects: {string.Join(", ", Subjects)}"; | |
} | |
} | |
internal class AnotherProgram | |
{ | |
private static void Main(string[] args) | |
{ | |
List<string> studentSubjects = new List<string> { "Maths", "English", "Physics" }; | |
Student author = new Student("John Doe", "[email protected]", studentSubjects); | |
Console.WriteLine(author); | |
// Oh, dear. We are able to change the subjects even after instantiation. | |
author.Subjects.Add("Chemistry"); | |
Console.WriteLine(author); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment