What does Enum.GetUnderlyingType (Type) do?

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

The MSDN documentation does not help:

Returns the base type of the specified enumeration.

This seems to convert the specified enum type to ... something else. o_o

What is the base type? This is similar to some internal implementation details. Why is this public? Why should I do this? Viewing the actual implementation also does not help, the method just performs some checks and then calls

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

... to which I cannot find the source.

Can anyone shed some light on this?

+4
source share
4 answers

Please note that you can specify the base type of an enumeration using

 enum Foo : long { One, Two }; 

And then GetUnderlyingType will return long for typeof(Foo) .

Note that the base type can be any integer type except char types.

+7
source

Enumerations are stored in memory as numbers. The default is int32. These are genuine types. You can change this:

 public enum z : byte { x = 257 // invalid } 
+5
source

Per MSDN :

Each enum type has a base type, which can be any integral type other than char. The default enumeration element type is int.

eg.

 enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; 

You are the base type - this is int

 enum Range :long {Max = 2147483648L, Min = 255L}; 

And now it is long.

+2
source

Here is a link to an article that gives some explanations about what it does and when to use it. http://dotnetperls.com/enum-getunderlyingtypepe

+1
source

Source: https://habr.com/ru/post/1334215/


All Articles