Skip to content

Repository files navigation

FastEnumToString

Source Generator generating ToString extension methods for any enums.

Configure

Global configuration: To set the fallback behaviour if no matching value is found.

<PropertyGroup>
<FastEnumDefaultBehaviour>Default</FastEnumDefaultBehaviour>
</PropertyGroup>

Or you can use the [ToString] attribute to override the global configuration by calling its parameterized constructor:

[ToString(ToStringDefault.First)]

Available values (for both):

  • Default: Uses the built-in Enum class behaviour and converts the provided value to its numeric representation
  • First: uses the first avalilable enum member,
  • Throw: throwing an ArgumentOutOfRangeException

*the csproj configuration is case insensitive

Example

usingFastEnumToString;usingMyNamespace;Colorcolor=(Color)5;Console.WriteLine(color);Console.WriteLine(color.FastToString());Console.WriteLine(NestingClass<int,List<int>>.NestedInClassEnum.None.FastToString());Console.WriteLine(EnumStringConverter.FastToString(NestingClass<int,List<int>>.NestedInClassEnum.None));namespaceMyNamespace{publicclassNestingClass<T,K>whereT:structwhereK:class,new(){[ToString]publicenumNestedInClassEnum{None}}[ToString(ToStringDefault.First)]publicenumColor{Red,Green,Blue,}// Flags are not fully supported,// only distinct values can be stringified[ToString,Flags]publicenumDevices{Phone=1,TV=2,Watch=4,}}

The followning will be generated:

// <auto-generated/>namespaceFastEnumToString{[global::System.CodeDom.Compiler.GeneratedCode("FastEnumToString","2.0.0")]publicstaticclassEnumStringConverter{publicstaticstringFastToString<T,K>(thisMyNamespace.NestingClass<T,K>.NestedInClassEnumenumValue)whereT:structwhereK:class,new()=>enumValueswitch{MyNamespace.NestingClass<T,K>.NestedInClassEnum.None=>nameof(MyNamespace.NestingClass<T,K>.NestedInClassEnum.None),
_ =>((int)enumValue).ToString()};publicstaticstringFastToString(thisMyNamespace.ColorenumValue)=>enumValueswitch{MyNamespace.Color.Red=>nameof(MyNamespace.Color.Red),MyNamespace.Color.Green=>nameof(MyNamespace.Color.Green),MyNamespace.Color.Blue=>nameof(MyNamespace.Color.Blue),
_ =>nameof(MyNamespace.Color.Red)};publicstaticstringFastToString(thisMyNamespace.DevicesenumValue)=>enumValueswitch{MyNamespace.Devices.Phone=>nameof(MyNamespace.Devices.Phone),MyNamespace.Devices.TV=>nameof(MyNamespace.Devices.TV),MyNamespace.Devices.Watch=>nameof(MyNamespace.Devices.Watch),
_ =>((int)enumValue).ToString()};}}

About

Source Generator generating ToString extension methods for any enums

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages