ClosedValues 1.0.0
See the version list below for details.
dotnet add package ClosedValues --version 1.0.0
NuGet\Install-Package ClosedValues -Version 1.0.0
<PackageReference Include="ClosedValues" Version="1.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="ClosedValues" Version="1.0.0" />
<PackageReference Include="ClosedValues"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add ClosedValues --version 1.0.0
#r "nuget: ClosedValues, 1.0.0"
#:package ClosedValues@1.0.0
#addin nuget:?package=ClosedValues&version=1.0.0
#tool nuget:?package=ClosedValues&version=1.0.0
ClosedValues
ClosedValues is a source generator and analyzer for closed value types. A closed value type is a class, record, struct or record struct with named members and a fixed set of static instances. Write the members and the instances. The generator writes the rest, and the analyzer keeps the set closed.
using ClosedValues;
[ClosedValue]
public sealed partial class Planet
{
public string Name { get; }
public int OrderFromSun { get; }
public bool IsInner => OrderFromSun <= 4;
public static readonly Planet Mercury = new("Mercury", 1);
public static readonly Planet Venus = new("Venus", 2);
public static readonly Planet Earth = new("Earth", 3);
public static readonly Planet Mars = new("Mars", 4);
public static readonly Planet Jupiter = new("Jupiter", 5);
}
Generated members
| Member | Behaviour |
|---|---|
| Private constructor | One parameter per get-only auto-property, in declaration order. |
All |
Every static readonly instance, in declaration order. |
FromName(name), TryFromName(name, out result) |
Finds the instance by the name of its field, such as "Earth". The default comparison is ordinal; an overload takes a StringComparison. FromName throws an ArgumentException for an unknown name. |
TryParse(value, out result) |
Only when the type has exactly one member of a basic type: string, bool, char, a number type, DateTime or an enum. Finds the instance whose member equals value. A string member also gets an overload with a StringComparison; the default comparison is ordinal. |
Parse(value) |
Like TryParse, but throws an ArgumentException when no instance has the value. |
| Conversions | Under the same condition as TryParse: an implicit conversion to the member, and an explicit conversion from it that calls Parse. |
Match<TResult>(...) |
One Func<TResult> per instance. A new instance adds a parameter, so every call site stops compiling until it handles the new instance. |
Match<TResult>(@default, ...) |
A fallback @default and an optional Func<TResult> per instance. Handles a few instances and sends the rest to @default. This overload does not stop compiling for a new instance. When an instance is named Default, the fallback is _ instead. |
Equals, GetHashCode, ==, != |
Compare the get-only auto-properties. A record gets these from the compiler instead. |
CompareTo, <, <=, >, >= |
Only when the type has exactly one member of a basic type other than bool or string. Orders the instances by that member, and implements IComparable<T>. |
ToString |
Returns the first string member. The generator skips it when the type has no string member. |
Computed properties, such as IsInner, stay yours. The generator ignores them.
int moons = planet.Match(
mercury: () => 0,
venus: () => 0,
earth: () => 1,
mars: () => 2,
jupiter: () => 95);
bool hasMoons = planet.Match(@default: () => true, mercury: () => false, venus: () => false);
Planet earth = Planet.FromName("Earth");
A Match parameter that is a C# keyword gets an @ prefix: an instance Default becomes @default.
A class works directly with dependency injection: services.AddSingleton(Planet.Earth).
JSON and text conversion
The generator adds two nested converters and applies them to the type with attributes:
| Converter | Used by |
|---|---|
ClosedValueJsonConverter |
System.Text.Json, through [JsonConverter]. Also converts dictionary keys. |
ClosedValueTypeConverter |
TypeDescriptor, through [TypeConverter]: ASP.NET Core model binding of route and query values, configuration binding, and property grids. |
Both write one value per instance:
- The single member, when the type has exactly one member of a basic type other than an enum.
Priority.Highbecomes3andVisibility.Publicbecomes"public". - The field name otherwise.
Planet.Earthbecomes"Earth".
Reading an unknown value throws a JsonException or a FormatException. Text uses the invariant culture.
The generator skips an attribute when the type already has its own [JsonConverter] or [TypeConverter],
and it skips the JSON converter when the project does not reference System.Text.Json.
System.Text.Json source generation (a JsonSerializerContext, as used for Native AOT) does not work with closed
value types. Source generators cannot see each other's output, so the JSON generator sees neither the generated
constructor nor the generated converter, and it fails to compile metadata for the type. Use the default
reflection-based serializer, or keep closed values out of the types that a JsonSerializerContext covers.
Records and structs
[ClosedValue] also works on a sealed record, a struct and a record struct. The rules for the members are the
same: get-only auto-properties, no own constructor, and partial.
[ClosedValue]
public readonly partial record struct Coin
{
public int Cents { get; }
public static readonly Coin Penny = new(1);
public static readonly Coin Nickel = new(5);
public static readonly Coin Dime = new(10);
}
| Kind | Differences |
|---|---|
| Record | Keeps the equality and == of the compiler. Match compares values, so a copy made with with { } still matches its instance. A record must be sealed and must not be positional. |
| Struct | The generator writes value equality and IEquatable<T>. TryParse returns the default value when nothing matches. |
| Record struct | Keeps the equality of the compiler, like a record. Behaves like a struct otherwise. |
A struct always has a default value, with every member set to its own default. That value is none of the
instances: Match throws for it. The analyzer reports default and new() outside the type
(CV0006, CV0001), but an array element or an unassigned field
still holds the default value. Choose a struct when the values are small and the default value is not a
risk, and a class otherwise.
Examples
The project samples/ClosedValues.Examples is a console application with three examples:
| Example | Shows |
|---|---|
OrderStatus |
One string member: TryParse, FromName, the conversions, Match with and without a fallback. |
Currency |
Two members: an ISO 4217 code and its decimal places, and a Format method that reads both. |
SubscriptionPlan |
Four members: computed properties, queries over All, a dictionary key, an exhaustive Match, and the plan injected into a service through dependency injection. |
dotnet run --project samples/ClosedValues.Examples
Rules
| Rule | Reports |
|---|---|
| CV0001 | A new of the type outside its own body, including new() on a struct. |
| CV0002 | An own instance constructor or a primary constructor. |
| CV0003 | A type that is not partial. |
| CV0004 | A class or record that is not sealed. |
| CV0005 | A settable or init-only auto-property, or an instance field. |
| CV0006 | The default value of a struct outside its own body. |
| CV0007 | A nested, generic, static or ref struct type. |
| CV0008 | A member with the name of a generated member, such as All or Match. |
All rules are errors by default.
Requirements
- A compiler with Roslyn 4.14 or later: the .NET SDK 9.0.300, or Visual Studio 2022 17.14. The generator
needs this version to mark its attribute as embedded, so that projects with
InternalsVisibleTodo not see two copies of it. - C# 8 or later for nullable annotations in the generated code. Earlier versions get the same members without annotations.
Build
dotnet build ClosedValues.slnx
tests/ClosedValues.Tests/bin/Debug/net10.0/ClosedValues.Tests.exe
dotnet pack src/ClosedValues/ClosedValues.csproj -c Release -o artifacts
Learn more about Target Frameworks and .NET Standard.
This package has no dependencies.
NuGet packages (1)
Showing the top 1 NuGet packages that depend on ClosedValues:
| Package | Downloads |
|---|---|
|
ClosedValues.EntityFrameworkCore
EF Core value converters for ClosedValues types: a nested ValueConverter per closed value type, which stores the key or the field name, and a ConfigureClosedValues() method that registers them all. |
GitHub repositories
This package is not used by any popular GitHub repositories.