Sobes.tech
Junior — Middle

Selgitage, mida tähendab objektide loomine, mis pärast nende initsialiseerimist on muutumatud.

sobes.tech AI

Vastus AI-lt

Object creation that is immutable after initialization means that once an object is created and its fields are set, the state of that object cannot be changed. Such objects are called immutable.

In C#, this is achieved, for example, by:

  • declaring fields as readonly;
  • having only getters (no setters) in properties;
  • initializing all data through the constructor.

Advantages of immutable objects:

  • thread safety without additional synchronization.
  • simplification of code understanding, as the object's state does not change.
  • 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.