c# - What causes this strange behaviour of an enum? -


while messing around enums, found out strange behaviour of 1 of enums.

consider following code :

static void main()     {          console.writeline("values");         console.writeline();         foreach (month m in enum.getvalues(typeof(month)))         {             console.writeline(m.tostring());         }         console.writeline();         console.writeline("names");         console.writeline();         foreach (var m in enum.getnames(typeof(month)))         {             console.writeline(m);         }         console.readline();     }     public enum month     {         january,         may,         march,         april     } 

this code produces following output (as expected):

values  january may march april  names  january may march april 

now, lets change little bit enum, :

public enum month     {         january = 3,         may,         march,         april     } 

if run same code, same results apear (which strange is). if change enum :

public enum month     {         january = "g",         may,         march,         april     } 

i following compiler error :

cannot implicitly convert type 'string' 'int'.

why compiler allows me set 1 of values of enum 3, not g? , why first result second one? if changed value of january, why getvalues doesnt print 3?

by default, enums backed int. labels attached various int values. can either let compiler pick ints map each enum value to, or can explicitly.

you can create enums backed other numeric types, besides int (such byte or long).

the syntax this:

public enum month : long {     january = 50000000000, //note, big int32     may,     march,     april } 

you cannot have enum backed non-numeric type, such string.


Comments

Popular posts from this blog

How to run C# code using mono without Xamarin in Android? -

c# - SharpSsh Command Execution -

python - Specify path of savefig with pylab or matplotlib -