Immutable Type

Why Trust Techopedia

What Does Immutable Type Mean?

An immutable type, in the context of C#, is a type of object whose data cannot be changed after its creation. An immutable type sets the property or state of the object as read only because it cannot be modified after it is assigned during initialization.

Advertisements

Immutable types are designed for efficient memory management and better speed, which makes them suitable for objects with synchronization requirements. Immutability provides better code readability by making changes in program state visibility and isolating the operations that change state from those that do not. Immutable types provides higher security than mutable types.

An immutable type is used where data is to persist after being assigned once, but without any requirement for the data to be changed in the future. Because immutable objects do not change their state, they are more useful in multithread and multiprocess scenarios, as multiple threads may read or write an object, which may cause racing conditions and synchronization issues.

Techopedia Explains Immutable Type

Objects of immutable type can be created with the use of the keywords "const" and "readonly". While readonly allows modification of a field within the constructor, const does not. Numbers, strings and null can only be used as const fields, which are truly immutable. Readonly is not truly immutable because it allows writing only once. Thus, it is not a compile-time constant like the const field. Truly immutable objects never change their internal state at all and are therefore inherently thread-safe.

The System.String class is an immutable reference type provided in the .NET framework class library. This class creates a new string object internally for any string manipulation action. The contents of objects of this type do not change, although the syntax makes it appear as if contents can be changed. In addition, string is used as hash table key for the computation of hash values to avoid the risk of corrupting the hash data structure.

The main drawback of immutable types is that they require more resources than other object types.

Advertisements

Related Terms

Margaret Rouse
Editor

Margaret jest nagradzaną technical writerką, nauczycielką i wykładowczynią. Jest znana z tego, że potrafi w prostych słowach pzybliżyć złożone pojęcia techniczne słuchaczom ze świata biznesu. Od dwudziestu lat jej definicje pojęć z dziedziny IT są publikowane przez Que w encyklopedii terminów technologicznych, a także cytowane w artykułach ukazujących się w New York Times, w magazynie Time, USA Today, ZDNet, a także w magazynach PC i Discovery. Margaret dołączyła do zespołu Techopedii w roku 2011. Margaret lubi pomagać znaleźć wspólny język specjalistom ze świata biznesu i IT. W swojej pracy, jak sama mówi, buduje mosty między tymi dwiema domenami, w ten…