ReadOnly<T>

While C# (and the CLR in general) have several options for "read only" data, none of them are applicable to local variables (such as within a method).

This class provides SHALLOW immutability, as enforced by the internal variable's readonly modifier.

The class also provides an implicit operator TO (but not FROM) the originating data type, to make it easy to integrate into existing code.

Obviously there is nothing to stop a variable from being reassigned with a new instance of the class, but this at least provides indication to developers that the data should not change.
Language:
C#
Keywords:
C#;Immutable
Code Snippet

public class ReadOnly<T>

{

    private readonly T value;

    public ReadOnly(T Value) { this.value = Value; }

 

    public static implicit operator T (ReadOnly<T> inputObject) return inputObject.value; }

}

Example

ReadOnly<DateTime> _starttime = new ReadOnly<DateTime>(DateTime.Now);


Created 2012-05-24
comments powered by Disqus
Login