Pregunta de entrevista de EPAM Systems

How to make class as Immutable

Respuestas de entrevistas

Anónimo

27 oct 2024

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 }

Anónimo

27 oct 2024

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 }