How to enforce immutability to prevent the modification of values in C#

1 Answer

0 votes
// Immutable User Class in C# (Enforce Immutability)

using System;

// Immutable User class
public sealed class User
{
    // Private readonly fields → cannot be modified after construction
    private readonly int _id;
    private readonly string _name;

    // Public read‑only properties expose values safely
    public int Id => _id;
    public string Name => _name;

    // Constructor initializes all immutable fields exactly once
    public User(int id, string name)
    {
        _id = id;
        _name = name;
    }

    // No setters → immutability enforced
}

public class Program
{
    public static void Main()
    {
        // Create an immutable User object
        User u = new User(42, "Alexander");

        Console.WriteLine("ID: " + u.Id);
        Console.WriteLine("Name: " + u.Name);

        // The following lines would cause compile‑time errors:
        // u.Id = 100;          // ERROR: Property or indexer cannot be assigned to - it is read only
        // u.Name = "Alfred";   // ERROR: Property or indexer cannot be assigned to - it is read only
        // u._id = 100;         // ERROR: inaccessible due to its protection level
        // u._name = "Alfred";  // ERROR: inaccessible due to its protection level

        // The object is fully immutable
    }
}



/* 
run:

ID: 42
Name: Alexander

*/

 



answered 13 hours ago by avibootz
...