Skip to content
Konrad Jamrozik edited this page Jun 10, 2022 · 4 revisions

Notes on language limitations

Record constructors do not allow enforcing constraints

The problem:
How to guarantee that one cannot obtain an instance of given immutable record Foo, without checking for its invariants? For class types one can use private constructor and put the invariant checks in it, but record primary constructor is public.

Following classes require invariant checking upon instance creation:

Wikitools.AzureDevOps.WikiPageStats.DayStat
Wikitools.Lib.Primitives.DaySpan
Wikitools.AzureDevOps.ValidWikiPagesStats
Wikitools.Lib.Git.GitLogCommit.Numstat

I elaborate on this problem here: https://github.com/dotnet/csharplang/issues/4453#issuecomment-782807066
However, based on https://christianfindlay.com/2021/04/28/change-behavior-of-record-constructor/
I applied a workaround in DaySpan and WikiPageStats.DayStat, by still using record but abandoning primary constructor.

See also:
https://stackoverflow.com/questions/64309291/how-do-i-define-additional-initialization-logic-for-the-positional-record
https://stackoverflow.com/questions/69283960/is-it-possible-to-create-a-c-sharp-record-with-a-private-constructor

Clone this wiki locally