5

Suppose I have enum, which underlying type is byte:

enum EmpType : byte
{
    Manager = 1,
    Worker = 2,
}

Can I cast some int literal to underlying type of this enum(byte in this case) ?

Something like this doesn't work (Error: "; expected"):

byte x = (Enum.GetUnderlyingType(typeof(EmpType)))15;

Can I cast to underlying type without explicitly writing (byte)15 ?

Thanks.

8
  • This question makes no sense to me;. What are you trying to achieve with this shenanigan? Commented May 7, 2013 at 3:53
  • 1
    Enum.GetUnderlyingType returns a Type. So this is trying to cast 15 to class Type Commented May 7, 2013 at 3:53
  • @PieterGeerkens: He wants to do a cast to a type that is the underlying type of an enum, without having to specify again what that type is. Commented May 7, 2013 at 3:54
  • @Patashu: That's rather obvious. The question is why, because this is more a solution looking for a problem than a true problem. And what on earth id the point of attempting to cast 15 to an enum with values ranging from 1 to 2? Commented May 7, 2013 at 3:56
  • @Pieter Geerkens: This was just a theoretical question. I'm not going to implement it in real code. Just was wondering how to do that. And by the way, I'm not casting 15 to enum values of 1 or 2, I'm trying to cast to byte value. Commented May 7, 2013 at 4:09

2 Answers 2

6

I think the following will work. But I'm not sure it will get you the desired behavior in all cases.

var x = Convert.ChangeType(15, Enum.GetUnderlyingType(typeof(EmpType)))
Sign up to request clarification or add additional context in comments.

3 Comments

Glad to help! But be careful with it. It's pretty odd.
Even now in the future I found this very useful in a generic helper method that enumerates all flags in an enum, optionally retrieving the value of the underlying type.
Here's another valid and reasonable application: Treating enums as their underlying types in a switch statement that takes an object and has switch-on-type style cases.
0

I'm not entirely sure what you're trying to do. Below is a related question about casting ints to enums and vice-versa, the same applies to byte in this case.

Is it possible to cast integer to enum?

If you want to detect the underlying type at run-time... it seems awkward and a lot of work. You could just do a case statement based upon the name of the underlying type. I'm not sure what good it would do you due to type safety concerns.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.