6

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.

Aremyst
  • 1,480
  • 2
  • 19
  • 33
  • This question makes no sense to me;. What are you trying to achieve with this shenanigan? – Pieter Geerkens May 07 '13 at 03:53
  • 1
    Enum.GetUnderlyingType returns a Type. So this is trying to cast 15 to class Type – Steven Wexler May 07 '13 at 03: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. – Patashu May 07 '13 at 03: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? – Pieter Geerkens May 07 '13 at 03: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. – Aremyst May 07 '13 at 04:09
  • You should have stated that in your original post. Bad data will get you bad answers, and lose you friends. – Pieter Geerkens May 07 '13 at 04:11

2 Answers2

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)))
Steven Wexler
  • 16,589
  • 8
  • 53
  • 80
  • Glad to help! But be careful with it. It's pretty odd. – Steven Wexler May 07 '13 at 04:09
  • 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. – joakimriedel Sep 28 '20 at 16:45
  • 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. – M-Pixel Jan 05 '22 at 05:26
1

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.

Community
  • 1
  • 1
David Cummins
  • 972
  • 6
  • 15