Nett icon indicating copy to clipboard operation
Nett copied to clipboard

Case-insensitive enum parsing

Open alexrp opened this issue 5 years ago • 1 comments

Is there a way to parse enums in a case-insensitive way? At the moment, I'm doing (ProjectType)Enum.Parse(typeof(ProjectType), project.Get<string>("type"), true) since project.Get<ProjectType>("type") won't accept library as being equal to the enum member Library.

alexrp avatar Aug 06 '19 15:08 alexrp

Here is an example that creates custom toml settings with a case insensitive converter. You have to add a converter for each enum you are using in you config file.

public enum SomeEnum
{
    Value1,
    Value2
}

public class Obj
{
    public SomeEnum X { get; set; } = SomeEnum.Value1;
}

public class Example
{
    [Fact]
    public void RunExample()
    {
        var settings = TomlSettings.Create(cfg => cfg
            .ConfigureType<SomeEnum>(tc =>
                tc.WithConversionFor<TomlString>(conv => conv
                    .FromToml(s => (SomeEnum)Enum.Parse(typeof(SomeEnum), s.Value, ignoreCase: true))
                    .ToToml(e => e.ToString()))));

        var tml = @"
X = 'VALUE2'";

        var o = Toml.ReadString<Obj>(tml, settings);

        o.X.Should().Be(SomeEnum.Value2);
    }
}

Currently I'm thinking about, some config mechanism to allow to generally enable case insensitive enum conversion or if the default should be switched.

paiden avatar Aug 07 '19 15:08 paiden