Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Enum.GetUnderlyingType(Type) do?

Tags:

c#

.net

enums

I don't understand the purpose of Enum.GetUnderlyingType(Type enumType)

The MSDN documentation doesn't help either:

Returns the underlying type of the specified enumeration.

It seems that this converts a specified type of enum into... something else. o_O

What IS an underlying type? This looks like some internal details of the implementation. Why is this public? Why would I care about the implementation? Browsing the actual implementation doesn't help either, the method just does some checks then calls

[MethodImplAttribute(MethodImplOptions.InternalCall)] 
private static extern Type InternalGetUnderlyingType(Type enumType);

... to which I can't find the source.

Can anybody shed some light on this?

like image 806
Cristian Diaconescu Avatar asked Dec 06 '22 00:12

Cristian Diaconescu


2 Answers

Note that you can specify the underlying type of an enum via

enum Foo : long { One, Two };

And then GetUnderlyingType is going to return long for typeof(Foo).

Note that the underlying type can be any integral type except for char types.

like image 72
jason Avatar answered Dec 07 '22 14:12

jason


Enums are stored in memory as numbers. By default, int32. That's the underlyting type. You can change that:

public enum z : byte {
  x = 257 // invalid
}
like image 23
fejesjoco Avatar answered Dec 07 '22 14:12

fejesjoco