On System.Enum and System.ValueType


style="FONT-SIZE: 10pt; FONT-FAMILY: 'Courier New'">

style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">Yup color=black size=2> style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana">Shawn
style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">has it href="http://dotnetweblogs.com/SAVanNess/posts/5742.aspx">pretty much right
on.  Both System.Enum and
System.ValueType are themselves reference types. style="mso-spacerun: yes">   We added them to the system for
two primary reasons: "urn:schemas-microsoft-com:office:office" />


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> style="mso-tab-count: 1">           
1. We wanted to provide developers an easy way to group all ValueTypes
and all Enums in a class hierarchy.  


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> style="mso-tab-count: 1">           
2. We wanted to specialize the implementation of Equals and GetHashCode()
to be better quality (have less collisions) than was possible on
System.Object


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">The runtime does not use the base
classes of a type to determine if they are value or reference types. style="mso-spacerun: yes">  Instead it uses the metadata notations
/> style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana">Shawn face=Verdana color=black size=2> style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana"> points out. style="mso-spacerun: yes"> 


size=2> style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana"> 


size=2>As far
as the C# compiler… yup, looks like a bug. 
Notice I can do:


size=2> style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana"> 


size=2>IComparable c =
(IComparable) (Enum) Color.Red ;


size=2> style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana"> 


size=2>But,
this gives a compiler error


size=2> style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana"> 


size=2>IComparable c =
(IComparable) Color.Red ;


size=2> style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Verdana"> 


size=2>I asked
the guys on the C# design team about this and I am told it is fixed in the
latest build of “Whidbey”… (There is always the next version you
know).


face="Courier New" size=2>

Comments (2)

  1. Interesting stuff — thanks for providing some closure to my ramblings, Brad!

  2. Mark Hoffman says:

    Thank heavens for Google!

    I was adding some sorting capabilities into one of my classes today and received the compiler error when I tried to cast a member of my enum to IComparable. I was like "What the…Enum implements IComparable! Why can’t I cast it!?!"

    A quick Google search for "icomparable enum" led me here and to the solution of the additional cast to Enum. Works perfectly!