How to get the underlying value of an enum
Solution 1
Marking this as not correct, but I can't delete it.
Try this:
string value = (string)TransactionTypeCode.Shipment;
Solution 2
You have to check the underlying type of the enumeration and then convert to a proper type:
public enum SuperTasks : int
{
Sleep = 5,
Walk = 7,
Run = 9
}
private void btnTestEnumWithReflection_Click(object sender, EventArgs e)
{
SuperTasks task = SuperTasks.Walk;
Type underlyingType = Enum.GetUnderlyingType(task.GetType());
object value = Convert.ChangeType(task, underlyingType); // x will be int
}
Solution 3
I believe Enum.GetValues() is what you're looking for.
Solution 4
The underlying type of your enum is still int, just that there's an implicit conversion from char
to int
for some reason. Your enum is equivalent to
TransactionTypeCode { Shipment = 83, Receipt = 82, }
Also note that enum
can have any integral type as underlying type except char
, probably for some semantic reason. This is not possible:
TransactionTypeCode : char { Shipment = 'S', Receipt = 'R', }
To get the char
value back, you can just use a cast.
var value = (char)TransactionTypeCode.Shipment;
// or to make it more explicit:
var value = Convert.ToChar(TransactionTypeCode.Shipment);
The second one causes boxing, and hence should preform worse. So may be slightly better is
var value = Convert.ToChar((int)TransactionTypeCode.Shipment);
but ugly. Given performance/readability trade-off I prefer the first (cast) version..
Abhishek
I have been a senior developer with a focus on architecture, simplicity, and building effective teams for over ten years. As a director at Surge consulting I was involved in many operational duties and decisions and - in addition to software development duties - designed and implemented an interview processes and was involved in community building that saw it grow from 20 to about 350 developers and through an acquisition. I was then CTO setting up a dev shop at working closely with graduates of a coding bootcamp on both project work and helping them establish careers in the industry. Currently a Director of Engineering at findhelp.org your search engine for finding social services. I speak at conferences, have mentored dozens of software devs, have written popular articles, and been interviewed for a variety of podcasts and publications. I suppose that makes me an industry leader. I'm particularly interesting in companies that allow remote work and can check one or more of the following boxes: Product companies that help people in a non-trite manner (eg I'm not super interested in the next greatest way to get food delivered) Product companies that make developer or productivity tooling Funded startups that need a technical co-founder Functional programming (especially Clojure or Elixir) Companies trying to do something interesting with WebAssembly
Updated on April 01, 2021Comments
-
Abhishek about 3 years
I have the following enum declared:
public enum TransactionTypeCode { Shipment = 'S', Receipt = 'R' }
How do I get the value 'S' from a TransactionTypeCode.Shipment or 'R' from TransactionTypeCode.Receipt ?
Simply doing TransactionTypeCode.ToString() gives a string of the Enum name "Shipment" or "Receipt" so it doesn't cut the mustard.
-
Abhishek over 15 yearsActually its a little more complex, I copied the code wrong from my sample, you cannot have strings for values in an enum. so the full answer would be ((char)instance.Shipment),ToString()
-
Abhishek over 14 yearsI suppose if you don't know the underlying type of the enum this would be the way to do it. But how you would ever end up in that situation is beyond me.
-
jimr about 14 years+1 This is the last step I needed to automatically (through reflection) create my SP parameter-value list from an entity object. I can't save the enum to the database, so I'm saving the underlying value.
-
Jeppe Stig Nielsen almost 12 years@GeorgeMauer The "underlying type" of your enum is still
int
, so your definition really says:enum TransactionTypeCode { Shipment = 83, Receipt = 82, }
. There's an implicit conversion fromchar
toint
, for some reason. The only "problem" (which might be not a problem) with your enum is thatdefault(TransactionTypeCode)
does not have a name, since no member equals 0 (or'\0'
). -
kingfleur over 11 yearsThe Convert.ChangeType does need a FormatProvider, but for enums (which are basically ints), I think you can just pass null. +1 for the tip. @GeorgeMauer: I ended up with such a situation in SterlingDB, where all kind of types are serialzed to a file. So an object is passed to the serialize method. If it's an enum, we'll serialize the integer value, so we need the underlying value.
-
C.Evenhuis over 10 years@Peter whether
Convert.ChangeType
requires anIFormatProvider
depends on the framework you're working with. @GeorgeMauer I had to use it when communicating betweenAppDomains
where only one of them could load the enum type. -
Kirk Woll about 10 yearsThis answer is categorically wrong on every level. Start with the fact that it won't compile, and continue on to the fact that enums aren't strings, that characters aren't strings, and that the underlying type of the enum is not -- and cannot be -- a string.
-
Jens over 3 yearsOP tagged the question C# your code looks like java to me
-
Paul Childs about 3 years-1 This implies you know the ordering of the enum internally. E.g., one would be very much misled by this solution if they expected Shipment to be the first value of the enum.
-
Paul Childs about 3 years@GeorgeMauer all you need for that situation is peopleWorkingOnCodeBase > 1 || IsFinite(abilityToRememberImplicationsOfUnderlyingTypeDecision)