Skip to content

damien-o/EnumConstraints.Fody

Repository files navigation

EnumConstraints.Fody logo EnumConstraints.Fody

NuGet Version NuGet Downloads .net Status Activity Coverage CodeQL License Chat on Gitter

Validates enum property value.

See Milestones for release notes.

This is an add-in for Fody

It is expected that all developers using Fody become a Patron on OpenCollective. See Licensing/Patron FAQ for more information.

Usage

See also Fody usage.

NuGet installation

Install the EnumConstraints.Fody NuGet package and update the Fody NuGet package:

PM> Install-Package Fody
PM> Install-Package EnumConstraints.Fody

The Install-Package Fody is required since NuGet always defaults to the oldest, and most buggy, version of any dependency.

Add to FodyWeavers.xml

Add <EnumConstraints/> to FodyWeavers.xml

<Weavers>
  <EnumConstraints/>
</Weavers>

What it does

  • Looks for all classes with Properties.
  • Generates a new implementations of Set and Get methods.
  • Replaces orginal implementations with the new ones.
  • The new implementations are using the originals implementations under the hood

Behavior

public enum Status
{
    Value1,
    Value2,
}

public class Sample
{
    public Status Status { get; set;}
}

var sample = new();

sample.Status = Status.Value1; // Valid

sample.Status = (Status)10; // Throws an InvalidEnumValueException

How it works

The orginal lowered code

public class Sample
{
    private Status <Status>k__BackingField;

    public Status Status
    {
        get; // Calls get_Status
        set; // Calls set_Status
    }

    public Status get_Status()
    {
        return <Status>k__BackingField;
    }
    public void set_Status(Status value)
    {
        <Status>k__BackingField = value;
    }
}

What gets compiled

public class Sample
{
    private StringComparison <Status>k__BackingField;

    public Status Status
    {
        get; // Calls get_Status
        set; // Calls set_Status
    }

    public Status get_Status()
    {
        var value = get_Status_Unchecked();
        InvalidEnumValueException.ThrowIfInvalid(value);
        return value;
    }

    public void set_Status(Status value)
    {
        InvalidEnumValueException.ThrowIfInvalid(value);
        set_Status_Unchecked(value);
    }

    public Status get_Status_Unchecked
    {
        return <Status>k__BackingField;
    }
    public void set_Status_Unchecked(Status value)
    {
        <Status>k__BackingField = value;
    }
}

Icon

Checklist designed by Web Fonts.