23 Feb 2024
In C#, mutable and immutable refer to the state of objects and whether they can be changed after they are created.
-
Mutable: Mutable objects are those whose state can be modified after they are created. In C#, classes are mutable by default. This means you can change the properties and fields of an object even after it has been instantiated.
public class MutableExample { public int Value { get; set; } } MutableExample mutableObj = new MutableExample(); mutableObj.Value = 5; // Mutable
-
Immutable: Immutable objects, on the other hand, are objects whose state cannot be modified after they are created. In C#, strings, and many other primitive types like integers, floats, and structs, are immutable. Once they are created, their values cannot be changed.
string immutableString = "Hello"; // Immutable
When you manipulate an immutable object like a string, you're actually creating a new object rather than modifying the existing one. For example:
string originalString = "Hello"; string modifiedString = originalString + ", World"; // This creates a new string
In this case,
originalString
remains unchanged, andmodifiedString
contains the concatenated value.
Immutable objects have certain advantages, such as being inherently thread-safe and simplifying code reasoning in concurrent environments. However, they may have performance implications due to the creation of new objects when their values are "modified." Understanding the trade-offs between mutable and immutable objects is important in software design and development.