-3

While messing around with enums, I found out a strange behaviour of one of my enums.

Consider the 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 the following output (as expected):

Values

January
May
March
April

Names

January
May
March
April

Now, lets say I change a little bit my enum, like this :

public enum Month
    {
        January = 3,
        May,
        March,
        April
    }

If I run the same code, the same results will apear (which is strange as it is). Now if I change my enum like this :

public enum Month
    {
        January = "g",
        May,
        March,
        April
    }

I get the following compiler error :

Cannot implicitly convert type 'string' to 'int'.

Why the compiler allows me to set one of the values of the enum to 3, but not to g? And why the first result is exactly like the second one? If I changed the value of January, then why GetValues doesnt print 3?

Eminem
  • 870
  • 5
  • 20
  • Enum's are integers. While you see a word `January` it has a value of 1. (Or 3 as you assign it to have in your second example) But it cannot have the value of `g`. – crthompson Apr 01 '15 at 17:31
  • Read http://stackoverflow.com/a/16039343/380384 to see what you can do with an `enum`. – John Alexiou Apr 01 '15 at 17:35

3 Answers3

4

By default, enums are backed by an int. They are just labels attached to various int values. You can either let the compiler pick which ints to map each enum value to, or you can do it explicitly.

You can also create enums backed by other numeric types, besides int (such as byte or long).

The syntax would look like this:

public enum Month : long
{
    January = 50000000000, //note, too big for an int32
    May,
    March,
    April
}

You cannot have an enum backed by a non-numeric type, such as string.

Servy
  • 202,030
  • 26
  • 332
  • 449
2

This is how enumerations are implemented in C#, they can be based only on byte, int, long, short (and their unsigned analogs), you cannot use string as backing type.

nikis
  • 11,166
  • 2
  • 35
  • 45
0

Because there are only certain approved types for enums, and int is one of them.

9Deuce
  • 689
  • 13
  • 27