JPMorganChase Interview Question

how to make a class immutable

Interview Answers

Anonymous

Oct 30, 2020

There are two ways to implement the Immutable class. Approach #1 Read Only properties Parametrized constructor to initialize properties, public class Person { // Read-only properties. public string Name { get; } public string Article { get; private set; } // Public constructor. public Writer1(string authorName, string articleName) { Name = authorName; Article = articleName; } } Approach #2 Read-Only Properties Static method Private paramterized constructor to initialize properties, public class Person { // Read-only properties. public string Name { get; private set; } public string Article { get; } // Private constructor. private Writer2(string authorName, string articleName) { Name = authorName; Article = articleName; } // Public factory method. public static Writer2 GetArticle(string name, string article) { return new Writer2(name, article); } } It is important to note that read-only properties and a parameterized constructor are key to ingredients to the recipe of immutable classes.

Anonymous

Oct 30, 2020

There are two ways to implement the Immutable class. Approach #1 Read Only properties Parametrized constructor to initialize properties, public class Person { // Read-only properties. public string Name { get; } public string Article { get; private set; } // Public constructor. public Person(string authorName, string articleName) { Name = authorName; Article = articleName; } } Approach #2 Read-Only Properties Static method Private paramterized constructor to initialize properties, public class Person { // Read-only properties. public string Name { get; private set; } public string Article { get; } // Private constructor. private Person(string authorName, string articleName) { Name = authorName; Article = articleName; } // Public factory method. public static Person GetArticle(string name, string article) { return new Person(name, article); } } It is important to note that read-only properties and a parameterized constructor are key to ingredients to the recipe of immutable classes.