Skip to main content

EnumUtilities by Fabricio Godoy

Nuget / site data

Nuget GitHub last commit GitHub Repo stars

Details

Info

info

Name: EnumUtilities

Provides generic enum functions such as bitwise operations, fast HasFlag, and others.

Author: Fabricio Godoy

NuGet: https://www.nuget.org/packages/Raiqub.Generators.EnumUtilities/

You can find more details at https://github.com/skarllot/EnumUtilities

Source : https://github.com/skarllot/EnumUtilities

Original Readme

note

Enum Utilities

Build status OpenSSF Scorecard GitHub license Nuget Nuget

A source generator for C# that uses Roslyn to create extensions and parsers for enumerations

🏃 Quickstart   |   📗 Guide   |   📦 NuGet


A source generator for C# that uses Roslyn to create extensions and parsers for enumerations, allowing to get a value associated to enum member or parse back from attribute value to enum member. All code generated at compile time thus avoid using reflection or boilerplate code.

Compatibility

Raiqub.Generators.EnumUtilities runs with Roslyn compiler so does not introduce a new dependency to your project besides a library containing the EnumGenerator attribute.

It requires at least the .NET 6 SDK to run, but you can target earlier frameworks.

Quickstart

Add the package to your application using

dotnet add package Raiqub.Generators.EnumUtilities

Adding the package will automatically add a marker attribute, [EnumGenerator], to your project.

To use the generator, add the [EnumGenerator] attribute to an enum. For example:

[EnumGenerator]
public enum Categories
{
Electronics,
Food,
Automotive,
Arts,
BeautyCare,
Fashion
}

This will generate 3 classes with the following methods:

  • CategoriesExtensions
    • ToStringFast(this Categories)
    • IsDefined(this Categories)
    • InterlockedAdd(this ref Categories, int)
    • InterlockedDecrement(this ref Categories)
    • InterlockedIncrement(this ref Categories)
    • InterlockedCompareExchange(this ref Categories, Categories, Categories)
    • InterlockedExchange(this ref Categories, Categories)
  • CategoriesFactory
    • TryParse(string?, StringComparison, out Categories)
    • TryParseIgnoreCase(string?, out Categories)
    • TryParse(string?, out Categories)
    • TryParse(string?, StringComparison)
    • TryParseIgnoreCase(string?)
    • TryParse(string?)
    • GetValues()
    • GetNames()
  • CategoriesValidation
    • IsDefined(Categories)
    • IsDefined(string?, StringComparison)
    • IsDefinedIgnoreCase(string?)
    • IsDefined(string?)

Bit flags enums are supported too:

[Flags]
[EnumGenerator]
public enum Colours
{
Red = 1,
Blue = 2,
Green = 4,
}

Then 3 classes will be generated with the following methods:

  • ColoursExtensions
    • ToStringFast(this Colours)
    • IsDefined(this Colours)
    • InterlockedAnd(this ref Colours, Colours)
    • InterlockedOr(this ref Colours, Colours)
    • InterlockedCompareExchange(this ref Colours, Colours, Colours)
    • InterlockedExchange(this ref Colours, Colours)
  • ColoursFactory
    • TryParse(string?, StringComparison, out Colours)
    • TryParse(string?, out Colours)
    • TryParseIgnoreCase(string?, out Colours)
    • TryParse(string?)
    • TryParseIgnoreCase(string?)
    • TryParse(string?, StringComparison)
    • GetValues()
    • GetNames()
  • ColoursValidation
    • IsDefined(Colours)
    • IsDefined(string?, StringComparison)
    • IsDefinedIgnoreCase(string?)
    • IsDefined(string?)

All generated code are properly nullable annotated and removed from code coverage.

Guide

The following attributes are supported:

EnumMemberAttribute

Example:

[EnumGenerator]
public enum PaymentMethod
{
[EnumMember(Value = "Credit card")]
Credit,
[EnumMember(Value = "Debit card")]
Debit,
Cash,
Cheque
}

This will generate the following methods:

  • PaymentMethodExtensions
    • ToEnumMemberValue(this PaymentMethod)
  • PaymentMethodFactory
    • TryParseFromEnumMemberValue(string?, StringComparison, out PaymentMethod)
    • TryParseFromEnumMemberValue(string?, out PaymentMethod)
    • TryParseFromEnumMemberValue(string?, StringComparison)
    • TryParseFromEnumMemberValue(string?)

DescriptionAttribute

Example:

[EnumGenerator]
public enum PaymentMethod
{
Credit,
Debit,
[Description("The payment by using physical cash")]
Cash,
Cheque
}

This will generate the following methods:

  • PaymentMethodExtensions
    • GetDescription(this PaymentMethod)
  • PaymentMethodFactory
    • TryCreateFromDescription(string?, StringComparison, out PaymentMethod)
    • TryCreateFromDescription(string?, out PaymentMethod)
    • TryCreateFromDescription(string?, StringComparison)
    • TryCreateFromDescription(string?)

DisplayAttribute

Example:

[EnumGenerator]
public enum WeekDays
{
[Display(
Name = nameof(Strings.MondayFull),
ShortName = nameof(Strings.MondayShort),
Description = nameof(Strings.MondayDescription),
ResourceType = typeof(Strings))]
Monday,
[Display(ShortName = "Tue")]
Tuesday,
[Display]
Wednesday,
[Display(Name = "Thursday")]
Thursday,
[Display(Name = "Friday", ShortName = "Fri")]
Friday,
[Display(ShortName = "Sat", Description = "Almost the last day of the week")]
Saturday,
[Display(Description = "The last day of the week")]
Sunday
}

Note that if ResourceType is provided the generated code will correctly get the value from resource.

This will generate the following methods:

  • WeekDaysExtensions
    • GetDisplayShortName(this WeekDays)
    • GetDisplayName(this WeekDays)
    • GetDescription(this WeekDays)
  • WeekDaysFactory
    • TryCreateFromDisplayShortName(string?, StringComparison, out WeekDays)
    • TryCreateFromDisplayShortName(string?, out WeekDays)
    • TryCreateFromDisplayShortName(string?, StringComparison)
    • TryCreateFromDisplayShortName(string?)
    • TryCreateFromDisplayName(string?, StringComparison, out WeekDays)
    • TryCreateFromDisplayName(string?, out WeekDays)
    • TryCreateFromDisplayName(string?, StringComparison)
    • TryCreateFromDisplayName(string?)
    • TryCreateFromDescription(string?, StringComparison, out WeekDays)
    • TryCreateFromDescription(string?, out WeekDays)
    • TryCreateFromDescription(string?, StringComparison)
    • TryCreateFromDescription(string?)

JSON Serialization

Besides the member name, supports the EnumMemberAttribute and JsonPropertyNameAttribute attributes.

Example:

[JsonConverterGenerator]
[JsonConverter(typeof(SeasonJsonConverter))]
public enum Season
{
[EnumMember(Value = "\ud83c\udf31")]
Spring = 1,
[EnumMember(Value = "\u2600\ufe0f")]
Summer,
[EnumMember(Value = "\ud83c\udf42")]
Autumn,
[EnumMember(Value = "\u26c4")]
Winter
}

This will generate the following JSON converter: SeasonJsonConverter.

Contributing

If something is not working for you or if you think that the source file should change, feel free to create an issue or Pull Request. I will be happy to discuss and potentially integrate your ideas!

License

See the LICENSE file for details.

About

note

Enum to string- and multiple other extensions for an enum

How to use

Example ( source csproj, source files )

This is the CSharp Project that references EnumUtilities

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Raiqub.Generators.EnumUtilities" Version="1.6.14" />
</ItemGroup>
</Project>

Generated Files

Those are taken from $(BaseIntermediateOutputPath)\GX

// <auto-generated />
#nullable enable

using System;
using System.Runtime.CompilerServices;
using System.Threading;

#pragma warning disable CS1591 // publicly visible type or member must be documented

namespace EnumClassDemo
{
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Raiqub.Generators.EnumUtilities", "1.6.0.0")]
public static partial class ColorsExtensions
{
/// <summary>Converts the value of this instance to its equivalent string representation.</summary>
/// <returns>The string representation of the value of this instance.</returns>
public static string ToStringFast(this Colors value)
{
return value switch
{
Colors.None => nameof(Colors.None),
Colors.Red => nameof(Colors.Red),
Colors.Green => nameof(Colors.Green),
Colors.Blue => nameof(Colors.Blue),
_ => value.ToString()
};
}

/// <summary>Returns a boolean telling whether the value of this instance exists in the enumeration.</summary>
/// <returns><c>true</c> if the value of this instance exists in the enumeration; <c>false</c> otherwise.</returns>
public static bool IsDefined(this Colors value)
{
return ColorsValidation.IsDefined(value);
}

#if NET5_0_OR_GREATER
/// <summary>Bitwise "ands" two enumerations and replaces the first value with the result, as an atomic operation.</summary>
/// <param name="location">A variable containing the first value to be combined.</param>
/// <param name="value">The value to be combined with the value at <paramref name="location" />.</param>
/// <returns>The original value in <paramref name="location" />.</returns>
public static Colors InterlockedAnd(this ref Colors location, Colors value)
{
ref int locationRaw = ref Unsafe.As<Colors, int>(ref location);
int resultRaw = Interlocked.And(ref locationRaw, Unsafe.As<Colors, int>(ref value));
return Unsafe.As<int, Colors>(ref resultRaw);
}

/// <summary>Bitwise "ors" two enumerations and replaces the first value with the result, as an atomic operation.</summary>
/// <param name="location">A variable containing the first value to be combined.</param>
/// <param name="value">The value to be combined with the value at <paramref name="location" />.</param>
/// <returns>The original value in <paramref name="location" />.</returns>
public static Colors InterlockedOr(this ref Colors location, Colors value)
{
ref int locationRaw = ref Unsafe.As<Colors, int>(ref location);
int resultRaw = Interlocked.Or(ref locationRaw, Unsafe.As<Colors, int>(ref value));
return Unsafe.As<int, Colors>(ref resultRaw);
}
#endif

/// <summary>Compares two enumerations for equality and, if they are equal, replaces the first value.</summary>
/// <param name="location">The destination, whose value is compared with <paramref name="comparand" /> and possibly replaced.</param>
/// <param name="value">The value that replaces the destination value if the comparison results in equality.</param>
/// <param name="comparand">The value that is compared to the value at <paramref name="location" />.</param>
/// <returns>The original value in <paramref name="location" />.</returns>
public static Colors InterlockedCompareExchange(this ref Colors location, Colors value, Colors comparand)
{
ref int locationRaw = ref Unsafe.As<Colors, int>(ref location);
int resultRaw = Interlocked.CompareExchange(ref locationRaw, Unsafe.As<Colors, int>(ref value), Unsafe.As<Colors, int>(ref comparand));
return Unsafe.As<int, Colors>(ref resultRaw);
}

/// <summary>Sets an enumeration value to a specified value and returns the original value, as an atomic operation.</summary>
/// <param name="location">The variable to set to the specified value.</param>
/// <param name="value">The value to which the <paramref name="location" /> parameter is set.</param>
/// <returns>The original value of <paramref name="location" />.</returns>
public static Colors InterlockedExchange(this ref Colors location, Colors value)
{
ref int locationRaw = ref Unsafe.As<Colors, int>(ref location);
int resultRaw = Interlocked.Exchange(ref locationRaw, Unsafe.As<Colors, int>(ref value));
return Unsafe.As<int, Colors>(ref resultRaw);
}

public static string ToEnumMemberValue(this Colors value)
{
return value switch
{
Colors.None => "This should be never seen",
Colors.Red => nameof(Colors.Red),
Colors.Green => nameof(Colors.Green),
Colors.Blue => nameof(Colors.Blue),
_ => value.ToString()
};
}
}
}

Usefull

Download Example (.NET C# )

Share EnumUtilities

https://ignatandrei.github.io/RSCG_Examples/v2/docs/EnumUtilities

In the same category (Enum) - 4 other generators

CredFetoEnum

EnumClass

FusionReactor

NetEscapades.EnumGenerators