### Project file with NetEscapades.EnumGenerators PackageReference
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Example project file showing the PackageReference for NetEscapades.EnumGenerators. Do not use PrivateAssets when referencing this package because it has runtime dependencies.
```xml
Exe
net8.0
```
--------------------------------
### Project file referencing generator and runtime dependencies packages
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Example .csproj that references NetEscapades.EnumGenerators.Generators with PrivateAssets=All to avoid flowing dependencies, and optionally references NetEscapades.EnumGenerators.RuntimeDependencies. Use this approach when using the library internally and not wanting dependencies to flow to consumers.
```xml
Exe
net8.0
```
--------------------------------
### SerializationOptions Properties
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_False_EnumMemberAttribute_True_nodeps.verified.txt
Gets the configured serialization options: metadata attribute usage and transform.
```APIDOC
## SerializationOptions Properties
### Description
Gets the configured serialization options: metadata attribute usage and transform.
### Properties
- **UseMetadataAttributes** (bool) - Gets whether the value of any metadata attributes applied to an enum member should be used as the ToString() value for the enum. Defaults to false.
- **Transform** (SerializationTransform) - Gets the SerializationTransform to use during parsing. Defaults to None.
```
--------------------------------
### Configure analyzer severity via .editorconfig
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Optionally configure severity of individual analyzer rules using .editorconfig files. This example sets all built-in analyzers (NEEG004-NEEG012) to report as errors. Valid severity values: none, silent, suggestion, warning, error.
```ini
[*.{cs,vb}]
# NEEG004: Use ToStringFast() instead of ToString()
dotnet_diagnostic.NEEG004.severity = error
# NEEG005: Use HasFlagFast() instead of HasFlag()
dotnet_diagnostic.NEEG005.severity = error
# NEEG006: Use generated IsDefined() instead of Enum.IsDefined()
dotnet_diagnostic.NEEG006.severity = error
# NEEG007: Use generated Parse() instead of Enum.Parse()
dotnet_diagnostic.NEEG007.severity = error
# NEEG008: Use generated GetNames() instead of Enum.GetNames()
dotnet_diagnostic.NEEG008.severity = error
# NEEG009: Use generated GetValues() instead of Enum.GetValues()
dotnet_diagnostic.NEEG009.severity = error
# NEEG010: Use generated GetValuesAsUnderlyingType() instead of Enum.GetValuesAsUnderlyingType()
dotnet_diagnostic.NEEG010.severity = error
# NEEG011: Use generated TryParse() instead of Enum.TryParse()
dotnet_diagnostic.NEEG011.severity = error
# NEEG012: Call ToStringFast() on enum in StringBuilder.Append() for better performance
dotnet_diagnostic.NEEG012.severity = error
```
--------------------------------
### Package dependency tree for NetEscapades.EnumGenerators
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Shows the metapackage structure: NetEscapades.EnumGenerators references the Generators and RuntimeDependencies packages. The metapackage is the default for easy install; the generator and runtime dependencies flow transitively to referencing projects.
```text
NetEscapades.EnumGenerators
|____NetEscapades.EnumGenerators.Generators
|____NetEscapades.EnumGenerators.RuntimeDependencies
```
--------------------------------
### Build and test commands for NetEscapades.EnumGenerators
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/AGENTS.md
Nuke-based build commands for compiling, testing, packing, and running the full CI pipeline. Use the appropriate script for your platform (Windows: build.cmd, Unix: build.sh). The single test project command runs unit and integration tests directly with dotnet test, and the filter option runs a specific test by name.
```bash
# Build
./build.cmd Compile # Windows
./build.sh Compile # Unix
# Run all tests (unit + integration)
./build.cmd Test
./build.sh Test
# Run a single test project directly
dotnet test tests/NetEscapades.EnumGenerators.Tests
# Run a single test by name
dotnet test tests/NetEscapades.EnumGenerators.Tests --filter "FullyQualifiedName~CanGenerateEnumExtensionsInGlobalNamespace"
# Pack NuGet packages
./build.cmd Pack
# Full CI pipeline (clean + test + package tests)
./build.cmd Clean Test TestPackage
```
--------------------------------
### Interception examples: can and cannot intercept
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.Interceptors.md
Shows which ToString() calls can be intercepted and which cannot. Interception works only when the target type is unambiguously an interceptable enum; it fails for base types, implicit calls, and generic types.
```csharp
// All the examples in this method CAN be intercepted
public void CanIntercept()
{
var ok1 = Color.Red.ToString(); // ✅
var red = Color.Red;
var ok2 = red.ToString(); // ✅
var ok3 = "The colour is " + red.ToString(); // ✅
var ok4 = $"The colour is {red.ToString()}"; // ✅
}
// The examples in this method can NOT be intercepted
public void CantIntercept()
{
var bad1 = ((System.Enum)Color.Red).ToString(); // ❌ Base type
var bad2 = ((object)Color.Red).ToString(); // ❌ Base type
var bad3 = "The colour is " + red; // ❌ implicit
var bad4 = $"The colour is {red}"; // ❌ implicit
string Write(T val)
where T : Enum
{
return val.ToString(); // ❌ generic
}
}
```
--------------------------------
### Define NETESCAPADES_ENUMGENERATORS_USAGES in project file
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Add the DefineConstants entry to your .csproj to preserve [EnumExtensions] attribute usages in the build output. Without this, the [Conditional] attribute removes the attribute from reflection results at runtime. The example targets net8.0 and references NetEscapades.EnumGenerators version 1.0.0-beta21.
```xml
Exe
net8.0
$(DefineConstants);NETESCAPADES_ENUMGENERATORS_USAGES
```
--------------------------------
### Enable usage analyzers via .globalconfig
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Alternatively, add a .globalconfig file with this content to enable the analyzers. After using either configuration option, analyzers are enabled with default severity Warning.
```ini
is_global = true
build_property.EnumGenerator_EnableUsageAnalyzers = true
```
--------------------------------
### SerializationOptions.Transform Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesForcedInternalEnumCorrectly.verified.txt
Gets the SerializationTransform to use during parsing. By default, it's set to None, and the value is not transformed.
```APIDOC
## SerializationOptions.Transform Property
### Description
Gets the SerializationTransform to use during parsing. By default, it's set to None, and the value is not transformed.
### Property Signature
public SerializationTransform Transform { get; }
### Return Value
- **Type**: SerializationTransform
- **Description**: The transform to apply during serialization. Defaults to None.
### Remarks
- This property is read-only and set via the constructor.
```
--------------------------------
### SerializationOptions.Transform Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_True_nodeps.verified.txt
Gets the SerializationTransform to use during parsing. By default, it's set to SerializationTransform.None, and the value is not transformed.
```APIDOC
## SerializationOptions.Transform Property
### Description
Gets the SerializationTransform to use during parsing. By default, it's set to SerializationTransform.None, and the value is not transformed.
### Property
public SerializationTransform Transform { get; }
### Remarks
- Default value is SerializationTransform.None.
```
--------------------------------
### SerializationOptions.Transform Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_False_nodeps.verified.txt
Gets the SerializationTransform to use during parsing. By default, it's set to SerializationTransform.None, and the value is not transformed.
```APIDOC
## SerializationOptions.Transform Property
### Description
Gets the SerializationTransform to use during parsing. By default, it's set to SerializationTransform.None, and the value is not transformed.
### Property Signature
public SerializationTransform Transform { get; }
### Property Value
- **Type**: SerializationTransform
- **Default**: None
### Remarks
- The property returns the configured transform.
```
--------------------------------
### Benchmark results for ToStringFast vs ToString
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
BenchmarkDotNet output comparing ToStringFast() and ToString() across .NET Framework 4.8, .NET 6.0, and .NET 10.0. Shows ToStringFast is significantly faster and allocates no memory.
```ini
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1348 (20H2/October2020Update)
Intel Core i7-7500U CPU 2.70GHz (Kaby Lake), 1 CPU, 4 logical and 2 physical cores
DefaultJob : .NET Framework 4.8 (4.8.4420.0), X64 RyuJIT
.NET SDK=6.0.100
DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
```
--------------------------------
### EnumParseOptions.ComparisonType Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesForcedInternalEnumCorrectly.verified.txt
Gets the StringComparison to use during parsing. By default, it's set to Ordinal, and a case-sensitive comparison will be used.
```APIDOC
## EnumParseOptions.ComparisonType Property
### Description
Gets the StringComparison to use during parsing. By default, it's set to Ordinal, and a case-sensitive comparison will be used.
### Property Signature
public global::System.StringComparison ComparisonType { get; }
### Return Value
- **Type**: global::System.StringComparison
- **Description**: The StringComparison to use during parsing. Defaults to Ordinal if not set.
### Remarks
- The property returns the value of `_comparisonType` if set, otherwise the default `DefaultComparisonType` (Ordinal).
- This property is read-only.
```
--------------------------------
### EnumParseOptions.ComparisonType Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_True_nodeps.verified.txt
Gets the StringComparison to use during parsing. By default, it's set to StringComparison.Ordinal, and a case-sensitive comparison will be used.
```APIDOC
## EnumParseOptions.ComparisonType Property
### Description
Gets the StringComparison to use during parsing. By default, it's set to StringComparison.Ordinal, and a case-sensitive comparison will be used.
### Property
public global::System.StringComparison ComparisonType { get; }
### Remarks
- Default value is StringComparison.Ordinal.
```
--------------------------------
### Benchmark results table for ToStringFast vs ToString
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Benchmark results table showing mean time, error, standard deviation, ratio, and allocations for ToString and ToStringFast across net48, net6.0, and net10.0.
```markdown
| Method | FX | Mean | Error | StdDev | Ratio | Gen 0 | Allocated |
|------------- |-----------|-----------:|----------:|------------:|------:|-------:|----------:|
| ToString | `net48` | 578.276 ns | 3.3109 ns | 3.0970 ns | 1.000 | 0.0458 | 96 B |
| ToStringFast | `net48` | 3.091 ns | 0.0567 ns | 0.0443 ns | 0.005 | - | - |
| ToString | `net6.0` | 17.985 ns | 0.1230 ns | 0.1151 ns | 1.000 | 0.0115 | 24 B |
| ToStringFast | `net6.0` | 0.121 ns | 0.0225 ns | 0.0199 ns | 0.007 | - | - |
| ToString | `net10.0` | 6.4389 ns | 0.1038 ns | 0.0971 ns | 0.004 | 1.000 | 24 B |
| ToStringFast | `net10.0` | 0.0050 ns | 0.0202 ns | 0.0189 ns | 0.001 | - | - |
```
--------------------------------
### Project file with NetEscapades.EnumGenerators.Generators PackageReference
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.Generators.source.md
Shows a minimal .NET project file with the NetEscapades.EnumGenerators.Generators package reference. Marking the package as PrivateAssets="all" and ExcludeAssets="runtime" prevents transitive references and avoids copying the attributes DLL to build output.
```xml
Exe
net8.0
```
--------------------------------
### EnumParseOptions.ComparisonType Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_False_nodeps.verified.txt
Gets the StringComparison to use during parsing. By default, it's set to Ordinal, and a case-sensitive comparison will be used.
```APIDOC
## EnumParseOptions.ComparisonType Property
### Description
Gets the StringComparison to use during parsing. By default, it's set to Ordinal, and a case-sensitive comparison will be used.
### Property Signature
public global::System.StringComparison ComparisonType { get; }
### Property Value
- **Type**: global::System.StringComparison
- **Default**: Ordinal
### Remarks
- The property returns the configured comparison type, defaulting to Ordinal if not explicitly set.
```
--------------------------------
### EnumParseOptions Properties
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_False_EnumMemberAttribute_True_nodeps.verified.txt
Gets the configured parsing options: comparison type, metadata attribute matching, and number parsing enablement.
```APIDOC
## EnumParseOptions Properties
### Description
Gets the configured parsing options: comparison type, metadata attribute matching, and number parsing enablement.
### Properties
- **ComparisonType** (global::System.StringComparison) - Gets the StringComparison to use during parsing. Defaults to Ordinal.
- **AllowMatchingMetadataAttribute** (bool) - Gets whether the value of the selected metadata value attribute values applied to an enum should be used as the parse value for an enum. Defaults to false.
- **EnableNumberParsing** (bool) - Gets whether numbers should be parsed as a fallback when other parsing fails. Defaults to true.
```
--------------------------------
### Project file with NetEscapades.EnumGenerators.Interceptors PackageReference
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.Interceptors.md
Shows a minimal .NET 8 project file with the NetEscapades.EnumGenerators.Interceptors package reference. You can optionally mark the package as PrivateAssets="all" and ExcludeAssets="runtime".
```xml
Exe
net8.0
```
--------------------------------
### Example of enum ToString() call to be intercepted
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.Interceptors.md
Shows a typical call to ToString() on an enum that the interceptor will replace at compile-time with ToStringFast(). The enum Color is defined in the same snippet.
```csharp
var choice = Color.Red;
Console.WriteLine("You chose: " + choice.ToString());
public enum Color
{
Red = 0,
Blue = 1,
}
```
--------------------------------
### Reference NetEscapades.EnumGenerators metapackage
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Recommended for simplicity when you are the primary consumer or don't mind consumers referencing the generator package. Includes runtime dependencies transitively.
```xml
Exe
net8.0
```
--------------------------------
### Add NetEscapades.EnumGenerators package with dotnet CLI
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Use the dotnet CLI to add the NetEscapades.EnumGenerators package to your project. This command adds a PackageReference to your project file.
```bash
dotnet add package NetEscapades.EnumGenerators
```
--------------------------------
### SerializationOptions Constructor
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesForcedInternalEnumCorrectly.verified.txt
Creates an instance of SerializationOptions with configurable serialization behavior. Allows setting whether to use metadata attributes and the serialization transform to apply.
```APIDOC
## SerializationOptions Constructor
### Description
Creates an instance of SerializationOptions with configurable serialization behavior. Allows setting whether to use metadata attributes and the serialization transform to apply.
### Method
Constructor
### Signature
public SerializationOptions(
bool useMetadataAttributes = false,
SerializationTransform transform = SerializationTransform.None)
### Parameters
- **useMetadataAttributes** (bool) - Optional - Sets whether the value of any metadata value attribute values applied to an enum should be used in the ToStringFast call. Default is false.
- **transform** (SerializationTransform) - Optional - Sets the SerializationTransform to use when serializing the enum value. Default is None.
### Remarks
- The constructor initializes the properties `UseMetadataAttributes` and `Transform` with the provided values.
### Example
```csharp
var options = new SerializationOptions(
useMetadataAttributes: true,
transform: SerializationTransform.ToLower
);
```
```
--------------------------------
### EnumParseOptions.EnableNumberParsing Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesForcedInternalEnumCorrectly.verified.txt
Gets a value defining whether numbers should be parsed as a fallback when other parsing fails. By default, it's set to true, and numbers will be parsed as well as names.
```APIDOC
## EnumParseOptions.EnableNumberParsing Property
### Description
Gets a value defining whether numbers should be parsed as a fallback when other parsing fails. By default, it's set to true, and numbers will be parsed as well as names.
### Property Signature
public bool EnableNumberParsing { get; }
### Return Value
- **Type**: bool
- **Description**: True if number parsing is enabled; otherwise, false.
### Remarks
- This property is read-only and derived from the `enableNumberParsing` constructor parameter.
- It returns the negation of `_blockNumberParsing`.
```
--------------------------------
### Generated MyEnumExtensions class for preview language version
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/EnumGeneratorTests.PreviewLangVersionDoesntGenerateExtensionMembers.verified.txt
Snapshot of the generated extension class when the preview language version is used. It includes ToStringFast overloads and private lower/upper invariant helpers, but omits extension members that would require preview features.
```csharp
//------------------------------------------------------------------------------
//
// This code was generated by the NetEscapades.EnumGenerators source generator
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS0612 // Ignore usages of obsolete members or enums
#pragma warning disable CS0618 // Ignore usages of obsolete members or enums
///
/// Extension methods for
///
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("NetEscapades.EnumGenerators", "FIXED_VERSION")]
public static partial class MyEnumExtensions
{
///
/// The number of members in the enum.
/// This is a non-distinct count of defined names.
///
public const int Length = 2;
///
/// Returns the string representation of the value.
/// Directly equivalent to calling ToString() on .
///
/// The value to retrieve the string value for
/// The string representation of the value, the same as that returned by ToString()
public static string ToStringFast(this global::MyEnum value)
=> value switch
{
global::MyEnum.First => nameof(global::MyEnum.First),
global::MyEnum.Second => nameof(global::MyEnum.Second),
_ => value.AsUnderlyingType().ToString(global::System.Globalization.CultureInfo.InvariantCulture),
};
///
/// Returns the string representation of the value.
/// Directly equivalent to calling ToString() on .
///
/// The value to retrieve the string value for
/// The options to use when serializing the enum
/// The string representation of the value, using the provided options.
public static string ToStringFast(this global::MyEnum value, global::NetEscapades.EnumGenerators.SerializationOptions options)
=> options.Transform switch
{
global::NetEscapades.EnumGenerators.SerializationTransform.LowerInvariant => value.ToStringFastLowerInvariant(),
global::NetEscapades.EnumGenerators.SerializationTransform.UpperInvariant => value.ToStringFastUpperInvariant(),
_ => value.ToStringFast(),
};
private static string ToStringFastLowerInvariant(this global::MyEnum value)
=> value switch
{
global::MyEnum.First => "first",
global::MyEnum.Second => "second",
_ => value.AsUnderlyingType().ToString(global::System.Globalization.CultureInfo.InvariantCulture),
};
private static string ToStringFastUpperInvariant(this global::MyEnum value)
=> value switch
{
global::MyEnum.First => "FIRST",
global::MyEnum.Second => "SECOND",
_ => value.AsUnderlyingType().ToString(global::System.Globalization.CultureInfo.InvariantCulture),
};
///
/// Returns the string representation of the value.
/// If the member is decorated with the attribute
/// then that value is returned. Otherwise returns uses the name of the member,
/// equivalent to calling ToString() on .
///
/// The value to retrieve the string value for
/// If uses the value provided in the
/// attribute as the string representation of the member.
/// If , always uses the name of the member, the same as if ToString() was called.
/// The string representation of the value
public static string ToStringFast(this global::MyEnum value, bool useMetadataAttributes)
=> value.ToStringFast();
}
```
--------------------------------
### EnumParseOptions.EnableNumberParsing Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_True_nodeps.verified.txt
Gets a value defining whether numbers should be parsed as a fallback when other parsing fails. By default, it's set to true, and numbers will be parsed as well as names.
```APIDOC
## EnumParseOptions.EnableNumberParsing Property
### Description
Gets a value defining whether numbers should be parsed as a fallback when other parsing fails. By default, it's set to true, and numbers will be parsed as well as names.
### Property
public bool EnableNumberParsing { get; }
### Remarks
- Default value is true.
```
--------------------------------
### Reference Generators and RuntimeDependencies separately
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Alternative for reusable libraries: use Generators with PrivateAssets=All and ExcludeAssets="runtime", plus RuntimeDependencies to produce easier-to-consume APIs.
```xml
Exe
net8.0
```
--------------------------------
### EnumParseOptions.EnableNumberParsing Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_False_nodeps.verified.txt
Gets a value defining whether numbers should be parsed as a fallback when other parsing fails. By default, it's set to true, and numbers will be parsed as well as names.
```APIDOC
## EnumParseOptions.EnableNumberParsing Property
### Description
Gets a value defining whether numbers should be parsed as a fallback when other parsing fails. By default, it's set to true, and numbers will be parsed as well as names.
### Property Signature
public bool EnableNumberParsing { get; }
### Property Value
- **Type**: bool
- **Default**: true
### Remarks
- The property returns true if number parsing is enabled, false otherwise.
```
--------------------------------
### Enum with Display attribute and MetadataSource
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Shows how to use the [Display] attribute with the MetadataSource property set to DisplayAttribute so that methods like ToStringFast() and TryParse() can use the metadata value (e.g., "2nd") when useMetadataAttributes is true.
```csharp
[EnumExtensions(MetadataSource = MetadataSource.DisplayAttribute)]
public enum EnumWithDisplayNameInNamespace
{
First = 0,
[Display(Name = "2nd")]
Second = 1,
Third = 2,
}
```
--------------------------------
### Generated nested runtime dependencies when package is missing
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Shows that when the runtime dependencies package is not found, the generated code creates nested versions of EnumParseOptions, SerializationOptions, and SerializationTransform inside each generated extension method. This avoids downstream dependency requirements but makes consuming the APIs more verbose.
```csharp
namespace SomeNameSpace;
public static partial class MyEnumExtensions
{
// ... generated members
// The runtime dependencies are generated as nested types instead
public readonly struct EnumParseOptions { }
public readonly struct SerializationOptions
public enum SerializationTransform
}
```
--------------------------------
### Project-wide default metadata source via MSBuild property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Sets the default metadata source for the entire project by defining the EnumGenerator_EnumMetadataSource property. The value shown is EnumMemberAttribute, but you can also use DisplayAttribute or DescriptionAttribute.
```xml
EnumMemberAttribute
```
--------------------------------
### SerializationOptions Constructor
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_False_None_False_nodeps.verified.txt
Creates an instance of SerializationOptions with configurable serialization behavior, including metadata attribute usage and transform application.
```APIDOC
## SerializationOptions Constructor
### Description
Creates an instance of SerializationOptions with configurable serialization behavior, including metadata attribute usage and transform application.
### Method
Constructor
### Signature
`public SerializationOptions(bool useMetadataAttributes = false, SerializationTransform transform = SerializationTransform.None)`
### Parameters
- **useMetadataAttributes** (bool) - Optional - Whether to use metadata attribute values in ToStringFast. Defaults to false.
- **transform** (SerializationTransform) - Optional - The transform to apply when serializing. Defaults to None.
### Remarks
- Metadata attributes are ignored by default.
- No transform is applied by default.
```
--------------------------------
### SerializationOptions.UseMetadataAttributes Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesForcedInternalEnumCorrectly.verified.txt
Gets whether the value of any metadata attributes applied to an enum member should be used as the ToString() value for the enum. By default, it's set to false, so the value of metadata attributes on the enum values are ignored.
```APIDOC
## SerializationOptions.UseMetadataAttributes Property
### Description
Gets whether the value of any metadata attributes applied to an enum member should be used as the ToString() value for the enum. By default, it's set to false, so the value of metadata attributes on the enum values are ignored.
### Property Signature
public bool UseMetadataAttributes { get; }
### Return Value
- **Type**: bool
- **Description**: True if metadata attributes should be used for serialization; otherwise, false.
### Remarks
- This property is read-only and set via the constructor.
```
--------------------------------
### Generated TryParseWithCase with metadata attribute support
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Shows the generated TryParseWithCase method that optionally matches metadata attribute values (e.g., "2nd") when allowMatchingMetadataAttribute is true, then falls back to exact name matching and numeric parsing.
```csharp
private static bool TryParseWithCase(string? name, out MyEnum value, bool allowMatchingMetadataAttribute)
{
if (allowMatchingMetadataAttribute)
{
switch (name)
{
case "2nd":
value = MyEnum.Second;
return true;
default:
break;
};
}
switch (name)
{
case nameof(MyEnum.First):
value = MyEnum.First;
return true;
case nameof(MyEnum.Second):
value = MyEnum.Second;
return true;
case string s when int.TryParse(name, out var val):
value = (MyEnum)val;
return true;
default:
value = default;
return false;
}
}
```
--------------------------------
### SerializationOptions.UseMetadataAttributes Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_True_nodeps.verified.txt
Gets whether the value of any metadata attributes applied to an enum member should be used as the ToString() value for the enum. By default, it's set to false, so the value of metadata attributes on the enum values are ignored.
```APIDOC
## SerializationOptions.UseMetadataAttributes Property
### Description
Gets whether the value of any metadata attributes applied to an enum member should be used as the ToString() value for the enum. By default, it's set to false, so the value of metadata attributes on the enum values are ignored.
### Property
public bool UseMetadataAttributes { get; }
### Remarks
- Default value is false.
```
--------------------------------
### SerializationOptions.UseMetadataAttributes Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_False_nodeps.verified.txt
Gets whether the value of any metadata attributes applied to an enum member should be used as the ToString() value for the enum. By default, it's set to false, so the value of metadata attributes on the enum values are ignored.
```APIDOC
## SerializationOptions.UseMetadataAttributes Property
### Description
Gets whether the value of any metadata attributes applied to an enum member should be used as the ToString() value for the enum. By default, it's set to false, so the value of metadata attributes on the enum values are ignored.
### Property Signature
public bool UseMetadataAttributes { get; }
### Property Value
- **Type**: bool
- **Default**: false
### Remarks
- The property indicates whether metadata attributes are used for serialization.
```
--------------------------------
### Generated StringComparisonExtensions with ToStringFast and serialization options
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/InterceptorTests.CanInterceptUsingInterceptableAttributeToString.verified.txt
Snapshot of the source-generated extension class for System.StringComparison. Includes a Length constant, ToStringFast() switch expression, an overload using SerializationOptions with OverloadResolutionPriority, and private lower-invariant helper. The generated code is marked with #nullable enable and pragma warnings for obsolete members.
```C#
[
//------------------------------------------------------------------------------
//
// This code was generated by the NetEscapades.EnumGenerators source generator
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
#nullable enable
namespace System
{
#pragma warning disable CS0612 // Ignore usages of obsolete members or enums
#pragma warning disable CS0618 // Ignore usages of obsolete members or enums
///
/// Extension methods for
///
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("NetEscapades.EnumGenerators", "FIXED_VERSION")]
public static partial class StringComparisonExtensions
{
///
/// The number of members in the enum.
/// This is a non-distinct count of defined names.
///
public const int Length = 6;
///
/// Returns the string representation of the value.
/// Directly equivalent to calling ToString() on .
///
/// The value to retrieve the string value for
/// The string representation of the value, the same as that returned by ToString()
public static string ToStringFast(this global::System.StringComparison value)
=> value switch
{
global::System.StringComparison.CurrentCulture => nameof(global::System.StringComparison.CurrentCulture),
global::System.StringComparison.CurrentCultureIgnoreCase => nameof(global::System.StringComparison.CurrentCultureIgnoreCase),
global::System.StringComparison.InvariantCulture => nameof(global::System.StringComparison.InvariantCulture),
global::System.StringComparison.InvariantCultureIgnoreCase => nameof(global::System.StringComparison.InvariantCultureIgnoreCase),
global::System.StringComparison.Ordinal => nameof(global::System.StringComparison.Ordinal),
global::System.StringComparison.OrdinalIgnoreCase => nameof(global::System.StringComparison.OrdinalIgnoreCase),
_ => value.AsUnderlyingType().ToString(global::System.Globalization.CultureInfo.InvariantCulture),
};
///
/// Returns the string representation of the value.
/// Directly equivalent to calling ToString() on .
///
/// The value to retrieve the string value for
/// The options to use when serializing the enum
/// The string representation of the value, using the provided options.
#if !NETESCAPADES_ENUMGENERATORS_OMIT_OVERLOAD_PRIORITY
[global::System.Runtime.CompilerServices.OverloadResolutionPriority(1)]
#endif
public static string ToStringFast(this global::System.StringComparison value, global::NetEscapades.EnumGenerators.SerializationOptions options)
=> options.Transform switch
{
global::NetEscapades.EnumGenerators.SerializationTransform.LowerInvariant => value.ToStringFastLowerInvariant(),
global::NetEscapades.EnumGenerators.SerializationTransform.UpperInvariant => value.ToStringFastUpperInvariant(),
_ => value.ToStringFast(),
};
private static string ToStringFastLowerInvariant(this global::System.StringComparison value)
=> value switch
{
global::System.StringComparison.CurrentCulture => "currentculture",
global::System.StringComparison.CurrentCultureIgnoreCase => "currentcultureignorecase",
global::System.StringComparison.InvariantCulture => "invariantculture",
global::System.StringComparison.InvariantCultureIgnoreCase => "invariantcultureignorecase",
global::System.StringComparison.Ordinal => "ordinal",
global::System.StringComparison.OrdinalIgnoreCase => "ordinalignorecase",
_ => value.AsUnderlyingType().ToString(global::System.Globalization.CultureInfo.InvariantCulture),
};
```
--------------------------------
### Add [EnumExtensions] to an enum
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/fragments/enum-usage.include.md
Apply the [EnumExtensions] marker attribute to an enum to trigger source generation. The example includes an [EnumMember(Value = "2nd")] attribute on the Second member, which the generator uses for metadata-aware methods.
```csharp
[EnumExtensions]
public enum MyEnum
{
First,
[EnumMember(Value = "2nd")]
Second,
}
```
--------------------------------
### EnumParseOptions.AllowMatchingMetadataAttribute Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesForcedInternalEnumCorrectly.verified.txt
Gets whether the value of the selected metadata value attribute values applied to an enum should be used as the parse value for an enum. By default, it's set to false, so the value of any metadata attributes on the enum values are ignored.
```APIDOC
## EnumParseOptions.AllowMatchingMetadataAttribute Property
### Description
Gets whether the value of the selected metadata value attribute values applied to an enum should be used as the parse value for an enum. By default, it's set to false, so the value of any metadata attributes on the enum values are ignored.
### Property Signature
public bool AllowMatchingMetadataAttribute { get; }
### Return Value
- **Type**: bool
- **Description**: True if metadata attributes should be used for parsing; otherwise, false.
### Remarks
- This property is read-only and set via the constructor.
- When set to true, parsing will use the applicable MetadataSource for each enum member.
```
--------------------------------
### Runtime dependency types from NetEscapades.EnumGenerators.RuntimeDependencies
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
Shows the types provided by the runtime dependencies package: EnumParseOptions, SerializationOptions, and SerializationTransform. These are used by generated code when the package is referenced.
```csharp
namespace NetEscapades.EnumGenerators;
///
/// Defines the options use when parsing enums using members provided by NetEscapades.EnumGenerator.
///
public readonly struct EnumParseOptions { }
///
/// Options to apply when calling ToStringFast on an enum.
///
public readonly struct SerializationOptions
///
/// Transform to apply when calling ToStringFast
///
public enum SerializationTransform
```
--------------------------------
### Generated MyEnumExtensions class
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.md
The generator creates a partial class named MyEnumExtensions (by default) with helper methods like ToStringFast, IsDefined, Parse, and TryParse. The class uses the enum's members and metadata attributes.
```csharp
public static partial class MyEnumExtensions
{
public const int Length = 2;
public static string ToStringFast(this MyEnum value, bool useMetadataAttributes)
=> useMetadataAttributes ? value.ToStringFastWithMetadata() : value.ToStringFast();
public static string ToStringFast(this MyEnum value)
=> value switch
{
MyEnum.First => nameof(MyEnum.First),
MyEnum.Second => nameof(MyEnum.Second),
_ => value.ToString(),
};
private static string ToStringFastWithMetadata(this MyEnum value)
=> value switch
{
MyEnum.First => nameof(MyEnum.First),
MyEnum.Second => "2nd",
_ => value.ToString(),
};
public static bool IsDefined(MyEnum value)
=> value switch
{
MyEnum.First => true,
MyEnum.Second => true,
_ => false,
};
public static bool IsDefined(string name) => IsDefined(name, allowMatchingMetadataAttribute: false);
public static bool IsDefined(string name, bool allowMatchingMetadataAttribute)
{
var isDefinedInDisplayAttribute = false;
if (allowMatchingMetadataAttribute)
{
isDefinedInDisplayAttribute = name switch
{
"2nd" => true,
_ => false,
};
}
if (isDefinedInDisplayAttribute)
{
return true;
}
return name switch
{
nameof(MyEnum.First) => true,
nameof(MyEnum.Second) => true,
_ => false,
};
}
public static MyEnum Parse(string? name)
=> TryParse(name, out var value, false, false) ? value : ThrowValueNotFound(name);
public static MyEnum Parse(string? name, bool ignoreCase)
=> TryParse(name, out var value, ignoreCase, false) ? value : ThrowValueNotFound(name);
public static MyEnum Parse(string? name, bool ignoreCase, bool allowMatchingMetadataAttribute)
=> TryParse(name, out var value, ignoreCase, allowMatchingMetadataAttribute) ? value : throw new ArgumentException($"Requested value '{name}' was not found.");
public static bool TryParse(string? name, out MyEnum value)
=> TryParse(name, out value, false, false);
public static bool TryParse(string? name, out MyEnum value, bool ignoreCase)
=> TryParse(name, out value, ignoreCase, false);
public static bool TryParse(string? name, out MyEnum value, bool ignoreCase, bool allowMatchingMetadataAttribute)
=> ignoreCase
? TryParseIgnoreCase(name, out value, allowMatchingMetadataAttribute)
: TryParseWithCase(name, out value, allowMatchingMetadataAttribute);
private static bool TryParseIgnoreCase(string? name, out MyEnum value, bool allowMatchingMetadataAttribute)
{
if (allowMatchingMetadataAttribute)
{
switch (name)
{
case string s when s.Equals("2nd", System.StringComparison.OrdinalIgnoreCase):
value = MyEnum.Second;
return true;
default:
break;
};
}
}
```
--------------------------------
### EnumParseOptions.AllowMatchingMetadataAttribute Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_True_nodeps.verified.txt
Gets whether the value of the selected metadata value attribute values applied to an enum should be used as the parse value for an enum. By default, it's set to false, so the value of any metadata attributes on the enum values are ignored.
```APIDOC
## EnumParseOptions.AllowMatchingMetadataAttribute Property
### Description
Gets whether the value of the selected metadata value attribute values applied to an enum should be used as the parse value for an enum. By default, it's set to false, so the value of any metadata attributes on the enum values are ignored.
### Property
public bool AllowMatchingMetadataAttribute { get; }
### Remarks
- Default value is false.
```
--------------------------------
### EnumParseOptions.AllowMatchingMetadataAttribute Property
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/tests/NetEscapades.EnumGenerators.Tests/Snapshots/SourceGenerationHelperSnapshotTests.GeneratesEnumCorrectly_True_EnumMemberAttribute_False_nodeps.verified.txt
Gets whether the value of the selected metadata value attribute values applied to an enum should be used as the parse value for an enum. By default, it's set to false, so the value of any metadata attributes on the enum values are ignored.
```APIDOC
## EnumParseOptions.AllowMatchingMetadataAttribute Property
### Description
Gets whether the value of the selected metadata value attribute values applied to an enum should be used as the parse value for an enum. By default, it's set to false, so the value of any metadata attributes on the enum values are ignored.
### Property Signature
public bool AllowMatchingMetadataAttribute { get; }
### Property Value
- **Type**: bool
- **Default**: false
### Remarks
- Set to true to enable parsing using the applicable MetadataSource for each enum member.
```
--------------------------------
### Compiler replacement with ToStringFast()
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/NetEscapades.EnumGenerators.Interceptors.md
Shows the code that the compiler effectively replaces the original ToString() call with, as if the user had written ToStringFast() directly.
```csharp
// The compiler replaces the call with this 👇
Console.WriteLine("You chose: " + choice.ToStringFast());
```
--------------------------------
### Generated TryParse and GetValues/GetNames methods
Source: https://github.com/andrewlock/netescapades.enumgenerators/blob/main/docs/README.md
Shows the generated switch-based TryParse overloads (case-insensitive and with metadata attribute matching) and the GetValues/GetNames methods for an enum. The TryParseWithCase method first checks for metadata attribute values like "2nd" when allowMatchingMetadataAttribute is true.
```csharp
switch (name)
{
case string s when s.Equals(nameof(MyEnum.First), System.StringComparison.OrdinalIgnoreCase):
value = MyEnum.First;
return true;
case string s when s.Equals(nameof(MyEnum.Second), System.StringComparison.OrdinalIgnoreCase):
value = MyEnum.Second;
return true;
case string s when int.TryParse(name, out var val):
value = (MyEnum)val;
return true;
default:
value = default;
return false;
}
}
private static bool TryParseWithCase(string? name, out MyEnum value, bool allowMatchingMetadataAttribute)
{
if (allowMatchingMetadataAttribute)
{
switch (name)
{
case "2nd":
value = MyEnum.Second;
return true;
default:
break;
};
}
switch (name)
{
case nameof(MyEnum.First):
value = MyEnum.First;
return true;
case nameof(MyEnum.Second):
value = MyEnum.Second;
return true;
case string s when int.TryParse(name, out var val):
value = (MyEnum)val;
return true;
default:
value = default;
return false;
}
}
public static MyEnum[] GetValues()
{
return new[]
{
MyEnum.First,
MyEnum.Second,
};
}
public static string[] GetNames()
{
return new[]
{
nameof(MyEnum.First),
nameof(MyEnum.Second),
};
}
}
```