Forum Discussion

adamdiament's avatar
adamdiament
Occasional Visitor
5 years ago

C# Enum generation - underlying int values do not match the original enum

I created an enum on my server with integer values set manually rather than the default increment up from 0

public enum UserType
{
    Anonymous = 0,
    Customer = 10,
    Technician = 21,
    Manager = 25,
    Primary = 30
}

I am using AspNetCore.App 2.2.0 and swashbuckle aspnetcore 4.0.1 to generate my CSharp API client

The generated enum in the c sharp api client (using NSwag Studio for windows v 13.2.3.0) looks like this - the underlying integer values do not match the original enum.

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.1.5.0 (Newtonsoft.Json v11.0.0.0)")]
public enum UserType
{
    [System.Runtime.Serialization.EnumMember(Value = @"Anonymous")]
    Anonymous = 0,

    [System.Runtime.Serialization.EnumMember(Value = @"Customer")]
    Customer = 1,

    [System.Runtime.Serialization.EnumMember(Value = @"Technician")]
    Technician = 2,

    [System.Runtime.Serialization.EnumMember(Value = @"Manager")]
    Manager = 3,

    [System.Runtime.Serialization.EnumMember(Value = @"Primary")]
    Primary = 4,

}

This creates a problem for me client side as there are situations where I need to know the integer value. I am looking for a solution where I can avoid writing converters every time I want to know the integer value on the client side.

Option 1: Is there an option I am missing in either NSwag Studio or in .net configuration (my Startup.Cs config is below for reference) where I can force the generated enums to get the same integer values as the original enum?

Option 2: Alternatively if not, both my client and my server have access to the same original enum via a shared class library. Is there a way to get the generated api client to use the actual original enums in the apiclient.cs rather than generate its own?

Reference:

The enums part of my swagger generation code in Startup.Cs looks like this

services.AddJsonOptions(options =>
                    {                        options.
                            SerializerSettings.Converters.Add(new StringEnumConverter());
....services.AddSwaggerGen(setup =>
                  {                      setup.SwaggerDoc("v1", new Info { Title = AppConst.SwaggerTitle, Version = "v1" });                      setup.UseReferencedDefinitionsForEnums();
                      ... other stuff...
                  }

Matching SO question if you want some rep https://stackoverflow.com/questions/60222469/swagger-c-sharp-enum-generation-underlying-int-values-do-not-match-the-origina 

No RepliesBe the first to reply