Enum to string- and multiple other extensions for an enum
This is how you can use EnumUtilities .
The code that you start with is
<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>
The code that you will use is
using EnumClassDemo;
Console.WriteLine(Colors.None.ToStringFast());
Console.WriteLine(Colors.None.ToEnumMemberValue());
using Raiqub.Generators.EnumUtilities;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace EnumClassDemo;
[EnumGenerator]
[Flags]
//[JsonConverterGenerator]
//[JsonConverter(typeof(ColorJsonConverter))]
public enum Colors
{
//[Display(ShortName = "This should be never seen")]
[EnumMember(Value = "This should be never seen")]
None =0,
Red=1,
Green=2,
Blue=4,
}
The code that is generated is
// <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()
};
}
}
}
// <auto-generated />
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
#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 ColorsFactory
{
/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to
/// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
/// </summary>
/// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
/// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
/// <param name="result">
/// When this method returns, result contains an object of type Colors whose value is represented by value
/// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
/// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
/// </param>
/// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
/// <exception cref="ArgumentException"><paramref name="comparisonType"/> is not a <see cref="StringComparison"/> value.</exception>
public static bool TryParse(
[NotNullWhen(true)] string? name,
StringComparison comparisonType,
out Colors result)
{
switch (name)
{
case { } s when s.Equals(nameof(Colors.None), comparisonType):
result = Colors.None;
return true;
case { } s when s.Equals(nameof(Colors.Red), comparisonType):
result = Colors.Red;
return true;
case { } s when s.Equals(nameof(Colors.Green), comparisonType):
result = Colors.Green;
return true;
case { } s when s.Equals(nameof(Colors.Blue), comparisonType):
result = Colors.Blue;
return true;
case { } s when TryParseNumeric(s, comparisonType, out int val):
result = (Colors)val;
return true;
default:
return Enum.TryParse(name, out result);
}
}
/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to
/// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
/// </summary>
/// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
/// <param name="result">
/// When this method returns, result contains an object of type Colors whose value is represented by value
/// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
/// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
/// </param>
/// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
public static bool TryParse(
[NotNullWhen(true)] string? name,
out Colors result)
{
switch (name)
{
case nameof(Colors.None):
result = Colors.None;
return true;
case nameof(Colors.Red):
result = Colors.Red;
return true;
case nameof(Colors.Green):
result = Colors.Green;
return true;
case nameof(Colors.Blue):
result = Colors.Blue;
return true;
case { } s when TryParseNumeric(s, StringComparison.Ordinal, out int val):
result = (Colors)val;
return true;
default:
return Enum.TryParse(name, out result);
}
}
/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to
/// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
/// </summary>
/// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
/// <param name="result">
/// When this method returns, result contains an object of type Colors whose value is represented by value
/// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
/// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
/// </param>
/// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
public static bool TryParseIgnoreCase(
[NotNullWhen(true)] string? name,
out Colors result)
{
return TryParse(name, StringComparison.OrdinalIgnoreCase, out result);
}
/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to
/// an equivalent enumerated object.
/// </summary>
/// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
/// <returns>
/// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
/// If the parse operation fails, result contains <c>null</c> value.
/// </returns>
public static Colors? TryParse(string? name)
{
return TryParse(name, out Colors result) ? result : null;
}
/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to
/// an equivalent enumerated object.
/// </summary>
/// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
/// <returns>
/// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
/// If the parse operation fails, result contains <c>null</c> value.
/// </returns>
public static Colors? TryParseIgnoreCase(string? name)
{
return TryParse(name, StringComparison.OrdinalIgnoreCase, out Colors result) ? result : null;
}
/// <summary>
/// Converts the string representation of the name or numeric value of one or more enumerated constants to
/// an equivalent enumerated object.
/// </summary>
/// <param name="name">The case-sensitive string representation of the enumeration name or underlying value to convert.</param>
/// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
/// <returns>
/// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
/// If the parse operation fails, result contains <c>null</c> value.
/// </returns>
/// <exception cref="ArgumentException"><paramref name="comparisonType"/> is not a <see cref="StringComparison"/> value.</exception>
public static Colors? TryParse(string? name, StringComparison comparisonType)
{
return TryParse(name, comparisonType, out Colors result) ? result : null;
}
/// <summary>
/// Converts the string representation of the value associated with one enumerated constant to
/// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
/// </summary>
/// <param name="enumMemberValue">The value as defined with <see cref="System.Runtime.Serialization.EnumMemberAttribute"/>.</param>
/// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
/// <param name="result">
/// When this method returns, result contains an object of type Colors whose value is represented by value
/// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
/// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
/// </param>
/// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
/// <exception cref="ArgumentException"><paramref name="comparisonType"/> is not a <see cref="StringComparison"/> value.</exception>
public static bool TryParseFromEnumMemberValue(
[NotNullWhen(true)] string? enumMemberValue,
StringComparison comparisonType,
out Colors result)
{
switch (enumMemberValue)
{
case { } s when s.Equals("This should be never seen", comparisonType):
result = Colors.None;
return true;
case { } s when s.Equals(nameof(Colors.Red), comparisonType):
result = Colors.Red;
return true;
case { } s when s.Equals(nameof(Colors.Green), comparisonType):
result = Colors.Green;
return true;
case { } s when s.Equals(nameof(Colors.Blue), comparisonType):
result = Colors.Blue;
return true;
default:
result = default;
return false;
}
}
/// <summary>
/// Converts the string representation of the value associated with one enumerated constant to
/// an equivalent enumerated object. The return value indicates whether the conversion succeeded.
/// </summary>
/// <param name="enumMemberValue">The value as defined with <see cref="System.Runtime.Serialization.EnumMemberAttribute"/>.</param>
/// <param name="result">
/// When this method returns, result contains an object of type Colors whose value is represented by value
/// if the parse operation succeeds. If the parse operation fails, result contains the default value of the
/// underlying type of Colors. Note that this value need not be a member of the Colors enumeration.
/// </param>
/// <returns><c>true</c> if the value parameter was converted successfully; otherwise, <c>false</c>.</returns>
public static bool TryParseFromEnumMemberValue([NotNullWhen(true)] string? enumMemberValue, out Colors result)
{
return TryParseFromEnumMemberValue(enumMemberValue, StringComparison.Ordinal, out result);
}
/// <summary>
/// Converts the string representation of the value associated with one enumerated constant to
/// an equivalent enumerated object.
/// </summary>
/// <param name="enumMemberValue">The value as defined with <see cref="System.Runtime.Serialization.EnumMemberAttribute"/>.</param>
/// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
/// <returns>
/// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
/// If the parse operation fails, result contains a null value.
/// </returns>
/// <exception cref="ArgumentException"><paramref name="comparisonType"/> is not a <see cref="StringComparison"/> value.</exception>
public static Colors? TryParseFromEnumMemberValue(string? enumMemberValue, StringComparison comparisonType)
{
return TryParseFromEnumMemberValue(enumMemberValue, comparisonType, out Colors result) ? result : null;
}
/// <summary>
/// Converts the string representation of the value associated with one enumerated constant to
/// an equivalent enumerated object.
/// </summary>
/// <param name="enumMemberValue">The value as defined with <see cref="System.Runtime.Serialization.EnumMemberAttribute"/>.</param>
/// <returns>
/// Contains an object of type Colors whose value is represented by value if the parse operation succeeds.
/// If the parse operation fails, result contains a null value.
/// </returns>
public static Colors? TryParseFromEnumMemberValue(string? enumMemberValue)
{
return TryParseFromEnumMemberValue(enumMemberValue, StringComparison.Ordinal, out Colors result) ? result : null;
}
/// <summary>Retrieves an array of the values of the constants in the Colors enumeration.</summary>
/// <returns>An array that contains the values of the constants in Colors.</returns>
public static Colors[] GetValues()
{
return new[]
{
Colors.None,
Colors.Red,
Colors.Green,
Colors.Blue,
};
}
/// <summary>Retrieves an array of the names of the constants in Colors enumeration.</summary>
/// <returns>A string array of the names of the constants in Colors.</returns>
public static string[] GetNames()
{
return new[]
{
nameof(Colors.None),
nameof(Colors.Red),
nameof(Colors.Green),
nameof(Colors.Blue),
};
}
private static bool TryParseNumeric(
string name,
StringComparison comparisonType,
out int result)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return int.TryParse(name, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
case StringComparison.Ordinal:
case StringComparison.OrdinalIgnoreCase:
return int.TryParse(name, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out result);
default:
return int.TryParse(name, out result);
}
}
}
}
// <auto-generated />
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
#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 ColorsValidation
{
/// <summary>Returns a boolean telling whether the value of <see cref="Colors"/> instance exists in the enumeration.</summary>
/// <returns><c>true</c> if the value of <see cref="Colors"/> instance exists in the enumeration; <c>false</c> otherwise.</returns>
public static bool IsDefined(Colors value)
{
return value switch
{
Colors.None => true,
Colors.Red => true,
Colors.Green => true,
Colors.Blue => true,
_ => false
};
}
public static bool IsDefined(
[NotNullWhen(true)] string? name,
StringComparison comparisonType)
{
return name switch
{
{ } s when s.Equals(nameof(Colors.None), comparisonType) => true,
{ } s when s.Equals(nameof(Colors.Red), comparisonType) => true,
{ } s when s.Equals(nameof(Colors.Green), comparisonType) => true,
{ } s when s.Equals(nameof(Colors.Blue), comparisonType) => true,
_ => false
};
}
public static bool IsDefinedIgnoreCase([NotNullWhen(true)] string? name)
{
return IsDefined(name, StringComparison.OrdinalIgnoreCase);
}
public static bool IsDefined([NotNullWhen(true)] string? name)
{
return name switch
{
nameof(Colors.None) => true,
nameof(Colors.Red) => true,
nameof(Colors.Green) => true,
nameof(Colors.Blue) => true,
_ => false
};
}
}
}
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/EnumUtilities