By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,238 Members | 1,746 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,238 IT Pros & Developers. It's quick & easy.

cast IDictionary key type (.NET 2.0)

P: n/a
Hi

I have an OrderedDictionary object where the key is an enum. Is there an
easy way to cast it to an integer? Examples/document appreciated.

Thanks
Andrew
Sep 13 '06 #1
Share this Question
Share on Google+
10 Replies


P: n/a
Andrew,

If the key is returned to you as an object, then you have to cast it to
the enum type first, then an int, like so:

object key = ...;
int keyInt = (int) (EnumType) key;

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"J055" <j0**@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP06.phx.gbl...
Hi

I have an OrderedDictionary object where the key is an enum. Is there an
easy way to cast it to an integer? Examples/document appreciated.

Thanks
Andrew

Sep 13 '06 #2

P: n/a
Just curious, How come you cant go directly to an int?

Thanks.

--
Saad Rehmani / Prodika / Dallas / TX / USA
Andrew,

If the key is returned to you as an object, then you have to cast
it to the enum type first, then an int, like so:

object key = ...;
int keyInt = (int) (EnumType) key;
Hope this helps.

"J055" <j0**@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP06.phx.gbl...
>Hi

I have an OrderedDictionary object where the key is an enum. Is there
an easy way to cast it to an integer? Examples/document appreciated.

Thanks
Andrew

Sep 13 '06 #3

P: n/a
Saad,

Because when you unbox a value type, you have to unbox to the correct
type first. It's not a casting operation (although the syntax is the same).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Saad Rehmani" <sa**********@gmail.comwrote in message
news:44**************************@msnews.microsoft .com...
Just curious, How come you cant go directly to an int?
Thanks.

--
Saad Rehmani / Prodika / Dallas / TX / USA
>Andrew,

If the key is returned to you as an object, then you have to cast
it to the enum type first, then an int, like so:

object key = ...;
int keyInt = (int) (EnumType) key;
Hope this helps.

"J055" <j0**@newsgroups.nospamwrote in message
news:%2****************@TK2MSFTNGP06.phx.gbl...
>>Hi

I have an OrderedDictionary object where the key is an enum. Is there
an easy way to cast it to an integer? Examples/document appreciated.

Thanks
Andrew


Sep 13 '06 #4

P: n/a
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.comwrote:
Because when you unbox a value type, you have to unbox to the correct
type first. It's not a casting operation (although the syntax is the same).
No - for enums, you can unbox an enum to the underlying type of the
enum, or the underlying type to the enum. Here's a sample:

using System;

enum Foo
{
Bar, Baz
}

class Test
{
static void Main()
{
object boxedEnum = Foo.Bar;
int i = (int) boxedEnum;
Console.WriteLine (i);

object boxedInt = 1;
Foo x = (Foo) boxedInt;
Console.WriteLine (x);
}
}
Neither the C# spec nor the CLI spec correctly specify this behaviour -
or indeed any other reasonable behaviour, unfortunately.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Sep 13 '06 #5

P: n/a
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com>
wrote:
>Because when you unbox a value type, you have to unbox to the correct
type first. It's not a casting operation (although the syntax is the
same).
No - for enums, you can unbox an enum to the underlying type of the
enum, or the underlying type to the enum. Here's a sample:

<snip>

Neither the C# spec nor the CLI spec correctly specify this behaviour
- or indeed any other reasonable behaviour, unfortunately.
Yup.

I looked at the IL and its boxing / unboxing directly between the object
and int. No transient form seems to be required.

C#:
object boxedEnum = Foo.Bar;
int i = (int) boxedEnum;
Console.WriteLine (i);

IL:
L_0000: ldc.i4.0
L_0001: box Test.Class1/Foo
L_0006: stloc.0
L_0007: ldloc.0
L_0008: unbox int32
L_000d: ldind.i4
L_000e: stloc.1
L_000f: ldloc.1
L_0010: call void [mscorlib]System.Console::WriteLine(int32)
--
Saad Rehmani / Prodika / Dallas / TX / USA
Sep 13 '06 #6

P: n/a
Hi

I still don't know how to cast the keys of the IDictionary from an enum to
integer. I want to convert the whole collection. Do I need to get the
ICollection of keys and iterate through them one at a time?

Thanks again
Andrew


Sep 14 '06 #7

P: n/a
Following demonstrates this using both IDictionary and
IDictionary<TKey,TValue>; I recommend using the latter if you can, as it
avoids the box when obtaining the key, and is simpler as
IDictionary<TKey,TValue: IEnumerable<KeyValuePair<TKey,TValue>... but
you still need to cast the enum to the int manually:

using System;
using System.Collections;
using System.Collections.Generic;

enum SomeEnum { A = 200, B = 100, C = 50, D = 90}
class Program {

static void Main() {
// some demo data
Dictionary<SomeEnum, stringdata = new
Dictionary<SomeEnum,string>();
data.Add(SomeEnum.A, "a");
data.Add(SomeEnum.B, "b");
data.Add(SomeEnum.C, "c");
data.Add(SomeEnum.D, "d");
// convert using IDictionary
IDictionary idata = data; // non-typed interface to data
IDictionaryEnumerator enum1 = data.GetEnumerator();
Dictionary<int, stringnewData = new Dictionary<int,string>();
while(enum1.MoveNext()) {
newData.Add((int)(SomeEnum)enum1.Key, (string) enum1.Value);
}
// convert using IDictionary<T,T>
newData.Clear();
IDictionary<SomeEnum, stringgidata = data; // generic (typed)
interface to data
foreach(KeyValuePair<SomeEnum, stringpair in gidata) {
newData.Add((int) pair.Key, pair.Value);
}
}
}
Sep 14 '06 #8

P: n/a
I agree with Jon that for enums, you can unbox an enum to the underlying
type of the enum directly, as long as the variable has the same type of
underlying type of the enum.

Using following code snippet:

using System;

enum Foo : long
{
Bar, Baz
}

class Test
{
static void Main()
{
object boxedEnum = Foo.Bar;
int i1 = (int)(Foo)boxedEnum;
int i2 = (int)boxedEnum;
}
}

The i1 works correctly while i2 fails with InvalidCastException.

i1 works because we first unbox to the enum; then do a cast from long to
int which is ok.

i2 doesn't work because we cannot unbox a boxed long value to int.

Internally, here's exactly what happens when a boxed value type instance is
unboxed:
1. If the variable containing the reference to the boxed value type
instance is null, a NullReferenceException is thrown.
2. If the reference doesn't refer to an object that is boxed instance of
the desired value type, an InvalidCastException is thrown.

So I guess Nicholas's suggestion to unbox to the enum type first is more
safe if you don't know the underlying type of enum.
Here's some background information about enum:

======
When an enumerated type is compiled, the compiler turns each symbol into a
constant field of the type. For example:

internal struct Color : System.Enum {
public const Color White = (Color) 0;
public const Color Black = (Color) 1;

// Below is a public instance field containing a Color variable's
value
// You cannot write code that references this instance field
directly
public Int32 value__;
}

Note: the compiler won't actually compile this code because it forbids you
from defining a type derived from the special System.Enum type. However,
this pseudo-type definition shows you waht's happening internally.
Basically, an enumerated type is just a structure with a bunch of constant
fields defined in it and one instance field.

Every enumerated type has an underlying type, which can be a byte, sbyte,
short, ushort, int (the most common and default type), uint, long, or
ulong.

The compiler treats enumerated types as primitive types. As such, you can
use many of the familiar operators (==, !=, <, >, <=, >=, +, -, ^, &, |, ~,
++, and --) to manipulate enumerated type instances. All of these operators
actually work on the value__ instance field inside each enumerated type
instance.
======

Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 14 '06 #9

P: n/a
Hi Andrew,

I just saw your reply after I sent my previous post.

Besides Marc's answer to your question, do you need more input on your
question?

Yes you will have to interate through the collection's Keys and convert one
at a time.

Please reply to let us know whether or not your question is completely
answered.

Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 14 '06 #10

P: n/a
Hi Marc

I couldn't get the second example to work with my OrderedDictionary but the
first example works for me.

Thanks
Andrew

Sep 14 '06 #11

This discussion thread is closed

Replies have been disabled for this discussion.