0
public enum colurs
{
  red = '1',
  black = 2,
  green = 2
}

class Program
{

    static void Main(string[] args)
    {
        Console.WriteLine((int)colurs.red + ":" + colurs.red);
        Console.WriteLine((int)colurs.black + ":" + colurs.black);
        Console.WriteLine((int)colurs.green + ":" + colurs.green);
        Console.ReadLine();
    }
}

I excute this code and It gives Output like this

49:red
2:green
2:green

Hows this work? Why it gives value of black and green as green?Why it not gives as value of black and green as black?

  • Because green is the last value associated with 2. Doesn't matter anyway they are both 2... – Tony Hopkinson May 18 '15 at 08:54
  • 2
    And the first one - 49 is the conversion of char '1' to int. if you try `(char)49` you will get `1` in return. – Zohar Peled May 18 '15 at 08:55
  • 1
    When you have duplicate values in an enum, the name returned may appear to be picked by random. The `ToString` method calls `GetEnumName`, which has the default implementation to make a binary search for the value. Which value it finds depends on which one the binary search happens to find first; it's not guaranteed to be any specific one of the duplicates. – Guffa May 18 '15 at 09:03
  • Thanks lot.But if i intialise red =1 then it gives value of black and green as black.So is this due to random picked or We can predict about result? – user2577204 May 18 '15 at 09:06
  • @user2577204: no in that case green is green and black is black. [see here](http://ideone.com/SnMLPg). – Willem Van Onsem May 18 '15 at 09:19
  • @ CommuSoft: i checked your code but you change value of black as 1 .Dont change value of black,Just make value of red as 1(int not char) – user2577204 May 18 '15 at 09:41

0 Answers0