Windows Vista Beta | WinVistaBeta.com - Message | Explicit enum cast

November 23, 2008  
Subject: Explicit enum cast
Group: microsoft.public.msdn.general
Date: 6/13/2008 1:23:00 AM
From: =?Utf-8?B?VmxhZGltaXIgS25lemV2aWM=?= [Email Address Protection]

Hi!

I encountered a problem, which might be something I didn't understand quite
well. I'm using .NET 2.0.

Suppose you have an enum defined as:

public enum FooType : byte
{
Foo = 0,
Bar = 1
}

and you have the following code:

FooType foot = (FooType) 2;

What I expected here was InvalidCastException (or any other Exception) to be
thrown, but what really happened is that foot was assigned value 2.

If you check if submitted value is defined for particular enum using
Enum.IsDefined(typeof(FooType), (byte)2), you'll get 'false', but you'll be
able to assign it to FooType variable.

Am I missing something? Shouldn't enum limit values used for it?

Back
Subject: Re: Explicit enum cast
Group: microsoft.public.msdn.general
Date: 6/13/2008 1:42:24 AM
From: David Hearn [Email Address Protection]

Vladimir Knezevic wrote:
> Hi!
>
> I encountered a problem, which might be something I didn't understand quite
> well. I'm using .NET 2.0.
>
> Suppose you have an enum defined as:
>
> public enum FooType : byte
> {
> Foo = 0,
> Bar = 1
> }
>
> and you have the following code:
>
> FooType foot = (FooType) 2;
>
> What I expected here was InvalidCastException (or any other Exception) to be
> thrown, but what really happened is that foot was assigned value 2.
>
> If you check if submitted value is defined for particular enum using
> Enum.IsDefined(typeof(FooType), (byte)2), you'll get 'false', but you'll be
> able to assign it to FooType variable.
>
> Am I missing something? Shouldn't enum limit values used for it?

No. enums do not restrict the ability to set values outside of the
defined range. The only restriction is on the underlying type. In
essence an enum is just a way of using a value type but with helpful
naming to enhance readability.

D

Back