Re: enum is int
- From: "Peter Duniho" <NpOeStPeAdM@xxxxxxxxxxxxxxxx>
- Date: Tue, 29 Apr 2008 16:42:02 -0700
On Tue, 29 Apr 2008 16:26:04 -0700, jonpb <nospam@xxxxxxxxxx> wrote:
[...]
enum TestEnum { t1, t2 }
TestEnum te = TestEnum.t1;
int ti = (int)te;
if (te is int)
{
}
Why does the test for (te is int) fail?
IMHO, it's always a good idea to read _all_ of the documentation. In particular:
Note that the is operator only considers reference
conversions, boxing conversions, and unboxing
conversions. Other conversions, such as user-defined
conversions, are not considered.
The type conversion from an enum to an int is not: a reference conversion; a boxing conversion; or, an unboxing conversion.
Is there a work around for a function like this:
string CStr(Object arg)
{
if (arg is int)
{
}
}
other then always casting enums to ints?
I don't have Visual Studio handy at the moment, but I'm suspicious of the idea that a boxed enum would successfully be cast to an int. Generally, boxed values can only be cast to the exact type that they represent. Even if the types are compatible, attempting to unbox to the wrong type would usually throw an exception. My recollection is that this applies to enum-to-int conversions too.
Now, let's assume my recollection is wrong just for the sake of argument.. Assuming you could cast a boxed enum to an int, then I think you could do at least a couple of different things:
-- The simplest would be to just assume the cast will work. Whether this is appropriate or not depends on how you expect the code to be used.. But assuming you're not switching execution flow based on various types here and rather just doing some error checking, you can just define your method interface such that it requires valid data to be passed. The exception can be caught by the caller if they aren't sure they are passing the right data.
-- The next simplest would be to wrap the cast with a try/catch. Of course, similar to above, this might not be appropriate if you're potentially going to receive a lot of different types in the normal course of events, due to the computational cost of handling an exception. But if exceptions are rare, this would be reasonable.
-- Finally, if the object is an enum, then you might check for Enum first, cast to that and then use the Enum members to check the base type.. This of course assumes that you can cast a boxed enum to the Enum type, and I admit that without Visual Studio handy at the moment I'm unable to verify it. But it's something to try. I'd think if you could cast a boxed enum to an int, you could probably cast it to the Enum type. :)
Pete
.
- References:
- enum is int
- From: jonpb
- enum is int
- Prev by Date: Re: enum is int
- Next by Date: Re: enum is int
- Previous by thread: Re: enum is int
- Next by thread: sqldataadapter
- Index(es):
Relevant Pages
|