Unlimited reference types (again)

There are many questions in .NET about supporting non-empty reference types in .NET. The big hope was code contracts, but it was limited to checking the runtime for those with a limited budget.

Regarding approaches other than code contracts, John Skeet wrote a blog post about this a few years ago, and one of the commentators provided a useful view of NonNull struct in which IL was modified to disable the default constructor. This seems like a great approach, and I can assume that it expands it to provide all kinds of fuzzy microtypes . The manipulation of IL can be a post-assembly step, initiated by a structure attribute, for example.

//Microtype representing a non-zero age, so we want to disable the default ctor
[NoDefaultConstructor]
public struct Age
{
    public Age(int age)
    {
        // Implementation (including validation) elided
    }
} 

Before I explore this further, I would like to ask if anyone knows about any problems that may arise. I didn’t think about anything.

+5
source share
1 answer

This can be easily defeated - the runtime does not try to call the constructor without parameters (if present) in each script.

In particular, it will not be called when creating a struct-type array.

Age[] ages = new Age[3];

// This guy skips your "real" ctor as well as the "invalid" parameterless one.
Age age = ages[0];

... or in expressions default(structType):

// Invalid state here too.
Age age = default(Age);

From Jon Skeet's empirical research in this material, here is a list of other operations that are not called constructor:

  • Just declaring a variable, be it local, static, or instance
  • Boxing
  • Usage default(T)in the General Method
  • Usage new T()in the General Method

, , , - Age, , - , .

+6

All Articles