-3
class enum_class
{  
  public static void Main()   
  {       
    Gender Unknown = (int)Season.Winter;
    Console.WriteLine(Unknown);
    Console.WriteLine(Gender.Unknown);
  }
}

public enum Gender
{
   Unknown = 10;
}

public enum Season
{
   Winter = 1;
}

In the above code I wish to assign the value of variable Winter to variable Unknown. Now Console.WriteLine(Unknown); gives the expected output i.e. Unknown value is changed from its initial value 10 to 1.

However, Console.WriteLine(Gender.Unknown); prints 10 as its output which was its original value. May I know the reason behind this?!!

Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
SimpleGuy
  • 1
  • 1
  • You have created a variable of type `Gender` called `Unknown`, you haven't changed the value of the enum at all – Sayse Jan 21 '15 at 08:37
  • 1
    This question may help (not duplicate) - [Why does casting int to invalid enum value NOT throw exception?](http://stackoverflow.com/questions/6413804/why-does-casting-int-to-invalid-enum-value-not-throw-exception) – Sayse Jan 21 '15 at 08:38
  • 1
    You seem to have some basic confusion here about what [variables](https://msdn.microsoft.com/en-us/library/wew5ytx4(v=vs.90).aspx) are versus what [enums](https://msdn.microsoft.com/en-us/library/4s1w24dx(v=vs.90).aspx) are. – Damien_The_Unbeliever Jan 21 '15 at 08:38

1 Answers1

0

If we trace your code, we see that in the Main method, first you create a variable of Gender type (which is an enumeration) named unknown which is also equal to integer value of Season.Winter, that is 1. Therefore, Console.WriteLine(Unknown) will result in 1. In the third line, you call the value of Gender.Unknown; value of the enumeration you have defined, which is always 10.

To sum up; first Unknown in your code is a variable you created, but the second is Gender.Unknown which is a constant enumeration.

mcy
  • 1,209
  • 6
  • 25
  • 37