Make a Class Immutable in C#

 

  • sealed Keyword: Applying the sealed keyword to the class prevents it from being inherited. This is important for true immutability because a derived class could potentially introduce mutable behavior.

 

 

 

  • readonly Fields: Declare all instance fields as readonly. This ensures that the field can only be assigned a value in the constructor of the class or during its declaration. Once assigned, its value cannot be changed.

 

 

 

  • Do Not Provide Setters
    • Properties should be get-only, meaning there are no set accessors.

 

 


Related Question