Immutable type and property in C#

An immutable type is a type of which its properties can only be set at initialization. Once an object is created, nothing can be changed anymore. An immutable property is simply a read-only property.

In the following example, ImmutableType is an immutable type with one property Test. Test is a read-only property. It can only be set at construction.

class ImmutableType
{
    private readonly string _test;
    public string Test
    {
        get { return _test; }
    }

    public ImmutableType(string test)
    {
        _test = test;
    }
}

See also: The Wikipedia article, and some Stack Overflow questions on the topic.

Leave a Comment