cast IDictionary key type (.NET 2.0)

  • Thread starter Thread starter J055
  • Start date Start date
J

J055

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
 
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.
 
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 said:
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.
 
Nicholas Paldino said:
wrote:

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)
 
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
 
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, string> data = 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, string> newData = 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, string> gidata = data; // generic (typed)
interface to data
foreach(KeyValuePair<SomeEnum, string> pair in gidata) {
newData.Add((int) pair.Key, pair.Value);
}
}
}
 
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 ([email protected], 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.
 
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 ([email protected], 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.
 
Hi Marc

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

Thanks
Andrew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top