Wednesday, July 18, 2007

"as in C#" can be used with reference type or nullable types

ControlTypeEnum myEnum = Enum.ToObject(typeof(ControlTypeEnum),id) as ControlTypeEnum ;

here ControlTypeEnum as an Enum
and id is int value

will give an error
"Error 2 The as operator must be used with a reference type or nullable type ('ControlTypeEnum' is a non-nullable value type) "

because if type casting is not possible then in that case reference point to null, and in case of value type -we do not have the concept of null .

so .net 2.0 has concept of nullable types, like int?, float? (hay there is no string? - do u kow why ? think and u will get it.)

so proper syntex of the previous one is

ControlTypeEnum? myEnum = Enum.ToObject(typeof(ControlTypeEnum),id) as ControlTypeEnum ;

or

ControlTypeEnum myEnum = (ControlTypeEnum ) Enum.ToObject(typeof(ControlTypeEnum),id) ;


--thanks
Pradeep

No comments: