How to make class as Immutable
Anonymous
public class ImmutablePerson { // Fields are readonly to prevent modification after construction public string Name { get; } public int Age { get; } public IReadOnlyList Hobbies { get; } // Constructor initializes all properties public ImmutablePerson(string name, int age, List hobbies) { Name = name; Age = age; // Create a copy of the list to protect against external changes Hobbies = new List(hobbies).AsReadOnly(); } // Additional methods, if needed, can return new instances rather than modifying properties }
Check out your Company Bowl for anonymous work chats.