Skip to content

Instantly share code, notes, and snippets.

@way2datta
Created July 12, 2020 06:54
Show Gist options
  • Save way2datta/4174d4e7378bc31eeeb532995f56228c to your computer and use it in GitHub Desktop.
Save way2datta/4174d4e7378bc31eeeb532995f56228c to your computer and use it in GitHub Desktop.
Protect Your Immutable Object Invariants
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", "John@Doe.com", 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