Click here to Skip to main content
11,412,516 members (73,702 online)
Rate this: bad
good
Please Sign up or sign in to 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 30-Jan-13 5:00am
Comments
Anderso0on at 30-Jan-13 10:05am
   
this is wrong statment
// this wrong statement , must be implicitly ((i mean explicitly not implicitly ))cast
CHill60 at 30-Jan-13 10:12am
   
You can use the "Improve question" link to make the change in your original post if you like
CHill60 at 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 at 30-Jan-13 10:27am
   
thanks but this link can not explain my qus :(
boogac at 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

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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)
  Permalink  
Comments
Anderso0on at 30-Jan-13 10:51am
   
thanks OriginalGriff :)
OriginalGriff at 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
0 OriginalGriff 414
1 Sascha Lefévre 200
2 Maciej Los 155
3 ProgramFOX 130
4 Sergey Alexandrovich Kryukov 110
0 Sergey Alexandrovich Kryukov 9,025
1 OriginalGriff 7,247
2 Maciej Los 3,525
3 Abhinav S 3,248
4 Peter Leow 3,059


Advertise | Privacy | Mobile
Web02 | 2.8.150427.1 | Last Updated 30 Jan 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100