Junior — Middle
Explain what it means to create objects that are immutable after their initialization.
sobes.tech AI
Answer from AI
Creating objects that are immutable after their initialization means that once an object is created and its fields are set, the state of this object cannot be changed. Such objects are called immutable.
In C#, this can be achieved, for example, by:
- declaring fields as
readonly; - having only getters and no setters for properties;
- initializing all data through the constructor.
Advantages of immutable objects:
- Thread safety without additional synchronization.
- Simplifies understanding of the code, as the object's state does not change.
- Can be used as keys in collections and caches.
Example:
public class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
After creating an instance of Person, its properties cannot be changed.