Buda Gavril Buda Gavril - 1 year ago 186
C# Question

Invalid enum value

So I have a type:

public enum Types
aaa= 1,
bbb= 2,
ccc= 4

public class RequestPayload
public int Prop1 { get; set; }
public string Prop2 { get; set; }
public Types Prop3 { get; set; }

And with Postman I am testing a web api.

public MyType Create([FromBody] RequestPayloadpayload)
return null

Here are my postman settings:

enter image description here

So why in the controller my object has property
to 6666 when my enum does not have this value?

Answer Source

I don't know anything about "postman", but I assume you're surprised that an int value other than 1, 2, or 4 can be assigned to Prop3. The reason is - that's just how enums work in C# since under the hood a field of an enum type is converted to an int (or whatever the underlying type of the enum is), any int value can be stored in it.

From MSDN:

enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};  

A variable of type Days can be assigned any value in the range of the underlying type; the values are not limited to the named constants.

This is probably to avoid expensive run-time checking of values against "defined" values, but there may be other architectural reasons as well (the use of "flag" enums is one that comes to mind).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download