473,394 Members | 2,020 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

cast IDictionary key type (.NET 2.0)

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
10 3568
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: tshad | last post by:
The error I am getting is: ******************************************************************* Exception Details: System.InvalidCastException: Cast from type 'DBNull' to type 'String' is not...
3
by: William Mild | last post by:
I am porting old Dreamweaver generated ASP code to ASP.NET (VBScript to VB.NET). Error: Cast from type 'Field' to type 'Integer' is not valid The error occurs on the line which says "rsStudents =...
9
by: Ben | last post by:
Hello, I'm not a developper, so sorry if it's a stupid question... I'm trying to develop an application in vb.net and I have the following problem: I have some information in an array:...
5
by: AMDRIT | last post by:
I would like to cast an object to a value type specified by a variable of Type Function ReturnTest(InputVar as Object) as Object Dim DataType as Type = GetType(System.String) If TypeOf...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.