© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
36 replies
Thinker

Best way to do a discriminated union struct

I have a struct + enum that looks essentially like this.
public readonly struct Value
{
    public string? StringValue { get; } = null;
    public double? NumberValue { get; } = null;

    public ValueKind Kind { get; } 

    public bool IsUndefined => Kind == ValueKind.Undefined;
    [MemberNotNullWhen(true, nameof(StringValue))] 
    public bool IsString => Kind == ValueKind.String;
    [MemberNotNulWhen(true, nameof(NumberValue))] 
    public bool IsNumber => Kind == ValueKind.Number;

    public Value()
    {
        Kind = ValueKind.Undefined;
    } 
    public Value(string value) 
    {
        StringValue = value;
        Kind = ValueKind.String;
    } 
    public Value(double value)
    {
        NumberValue = value;
        Kind = ValueKind.Number;
    } 
}

public enum ValueKind
{
    Undefined, 
    String, 
    Number 
} 
public readonly struct Value
{
    public string? StringValue { get; } = null;
    public double? NumberValue { get; } = null;

    public ValueKind Kind { get; } 

    public bool IsUndefined => Kind == ValueKind.Undefined;
    [MemberNotNullWhen(true, nameof(StringValue))] 
    public bool IsString => Kind == ValueKind.String;
    [MemberNotNulWhen(true, nameof(NumberValue))] 
    public bool IsNumber => Kind == ValueKind.Number;

    public Value()
    {
        Kind = ValueKind.Undefined;
    } 
    public Value(string value) 
    {
        StringValue = value;
        Kind = ValueKind.String;
    } 
    public Value(double value)
    {
        NumberValue = value;
        Kind = ValueKind.Number;
    } 
}

public enum ValueKind
{
    Undefined, 
    String, 
    Number 
} 

Is there a better way to do this? Unfortunately I don't think it's possible to do the
MemberNotNullWhen
MemberNotNullWhen
thing but with just the enum.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ StructureMap.StructureMapException: StructureMap Exception Code: 207
C#CC# / help
3y ago
Best way to do this OOP-wise???
C#CC# / help
2y ago
✅ EF Best way to do UPDATE on entity
C#CC# / help
2y ago
Best way to trigger a Queued Email?
C#CC# / help
2y ago