Creating an immutable class in C# ensures that once an instance is created, its state cannot be modified. This is useful for Creating reliable and thread-safe objects. Here’s how you can achieve this:
1- Use readonly fields and initialize them through the constructor.
2- Avoid setters for properties.
3- Mark the class as sealed to prevent inheritance (optional).
Here’s a simple example:
public sealed class ImmutablePerson { public readonly string FirstName { get; } public readonly string LastName { get; } public ImmutablePerson(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } public string GetFullName() { return $"{FirstName} {LastName}" } } var person = new ImmutablePerson("John", "Doe"); Console.WriteLine(person.GetFullName());In this example:
1- The FirstName and LastName properties are read-only.
2- The only way to set FirstName and LastName is through the constructor.
3- The class is sealed to prevent modification through inheritance.