.netlinear-types

How to represent linear types in C#/.Net?


Is there a reasonable way to express the concept of a linear type in .Net (Compact Framework/desktop 3.5 common subset), in such a way that (a) the required syntax doesn't become overly verbose, convoluted, or otherwise painful and (b) the invariant can be either enforced at run time or validated by code analysis at compile time (so a maintenance programmer in an all-fired hurry can't just blithely ignore the invariant)? The idea here is to avoid the need for defensive copying of command objects at subsystem boundaries.


Solution

  • There are two kinds of types in .Net: reference types and value types.

    When you copy a reference type by assigning it to another variable, just the reference is copied.

    When you copy a value type, the whole content of the type is copied, byte by byte.

    In both cases, there is no way to prevent, modify or get notification about it (in contrast with C++'s copy constructors). What that means is that you can't implement linear types in .Net.

    Your can instead use immutable (or freezable) type, as others suggested.