bpeikes
bpeikes

Reputation: 3715

Is it possible in .Net to set integer enum to arbitrary value

For some reason the HttpResponseMessageProperty which I'm using to return specific HTTP response codes to a client uses a HttpStatusCode enumeration. This enumeration does not include 422, which is not included in the enum. Is there any way to set an enumeration using an integer since that's what it is under the covers?

Upvotes: 2

Views: 1006

Answers (3)

Dai
Dai

Reputation: 155678

Yes, it's possible - internally an enum value is just an integer and you can "force" an enum value to have an invalid value and the CLR will continue on its merry way.

for example:

enum Foo {
   Bar = 1,
   Baz = 2
}

void Test() {
    Foo foo; // as Foo is a value-type and no initial value is set, its value is zero.
    Console.WriteLine( foo ); // will output "0" even though there is no enum member defined for that value

    Foo foo2 = (Foo)200;
    Console.WriteLine( foo2 ); // will output "200"
}

This is why, when working with enum values of unknown provenance, you should always handle the default case and handle appropriately:

public void DoSomethingWithEnum(Foo value) {
    switch( value ) {
        case Foo.Bar:
            // do something
            break;
        case Foo.Baz:
            // do something else
            break;
        default:
            // I like to throw this exception in this circumstance:
            throw new InvalidEnumArgumentException( "value", (int)value, typeof(Foo) );
    }
}

Upvotes: 6

Xiaoy312
Xiaoy312

Reputation: 14477

You can cast any number into an enum, given the enum has the same base structure(usually it is int :

response.StatusCode = (HttpStatusCode)422;

Upvotes: 3

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

Yes, you can have any value you want (as long as it is in range of enum's base type wich usally is int):

HttpStatusCode value = (HttpStatusCode)422;

Upvotes: 2

Related Questions