Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C#
enum Gender
{
    male, female
}
class Program
{
    static void Main(string[] args)
    {
        Gender M = Gender.male;
        M = 0;
        //
        Gender F = Gender.female;
        F = 1; // this wrong statement , must be implicitly cast


    }
}

why we can just do implicitly cast for (zero), and another value must be explicit casting ??
Posted
Comments
Anderso0on 30-Jan-13 10:05am    
this is wrong statment
// this wrong statement , must be implicitly ((i mean explicitly not implicitly ))cast
CHill60 30-Jan-13 10:12am    
You can use the "Improve question" link to make the change in your original post if you like
CHill60 30-Jan-13 10:13am    
Have a look at these links to see if it helps explain it...
http://stackoverflow.com/questions/1260859/confusion-with-c-sharp-enum-and-explicit-conversion
and especially
http://stackoverflow.com/questions/4728295/why-enums-require-an-explicit-cast-to-int-type
They explain it far better than I can!
Anderso0on 30-Jan-13 10:27am    
thanks but this link can not explain my qus :(
boogac 30-Jan-13 10:38am    
cHill60's second link has a good answer..Philip Rieck commented that "enums do not have to be int based"

1 solution

Because the default value for any value type is zero - and an enum is a value type.
So you can always assign a zero to it (or it couldn't have a default value, which would be silly) but you can't assign any other integer value to it without casting it to an enum (to be sure you meant to do that, as it could generate values which are not part of the enumeration, particularly when you don't specify enum values, as you don't)
 
Share this answer
 
Comments
Anderso0on 30-Jan-13 10:51am    
thanks OriginalGriff :)
OriginalGriff 30-Jan-13 11:03am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900