Skip to main content

Posts

Showing posts with the label static abstract members

Generating types with build-in invariant preservation using C# source generators (1 / x) : Simple types

In an earlier post, I described a way for generating value types. In this post, I want to show how to take this a step further. Usually, one does not only want an alias but enforce an invariant using the type system at the same time.  So first let's recap what we mean by an invariant. Plainly put, an invariant is a condition that stays true no matter what happens. For example, let's suppose we have a value in our system that represents a quantity that must always be greater than zero. That is an invariant. Invariants pop up all over the place when modeling a domain. We want to enforce these invariants because we want to guard the integrity of our domain model. One very convenient way of guarding the integrity of values within the domain is by capturing invariants directly into the type system. Once you successfully create an instance of a type guarding the invariant, you never have to check its validity again. In addition to that, the validation logic is captured in 1 place, wh...