473,779 Members | 1,952 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

cast IDictionary key type (.NET 2.0)

Hi

I have an OrderedDictiona ry 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 3608
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.co m

"J055" <j0**@newsgroup s.nospamwrote in message
news:%2******** ********@TK2MSF TNGP06.phx.gbl. ..
Hi

I have an OrderedDictiona ry 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**@newsgroup s.nospamwrote in message
news:%2******** ********@TK2MSF TNGP06.phx.gbl. ..
>Hi

I have an OrderedDictiona ry 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.co m

"Saad Rehmani" <sa**********@g mail.comwrote in message
news:44******** *************** ***@msnews.micr osoft.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**@newsgroup s.nospamwrote in message
news:%2******* *********@TK2MS FTNGP06.phx.gbl ...
>>Hi

I have an OrderedDictiona ry 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.c omwrote:
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.WriteLi ne (i);

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

--
Jon Skeet - <sk***@pobox.co m>
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.c om>
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.WriteLi ne (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(int3 2)
--
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<TKe y,TValue>; I recommend using the latter if you can, as it
avoids the box when obtaining the key, and is simpler as
IDictionary<TKe y,TValue: IEnumerable<Key ValuePair<TKey, TValue>... but
you still need to cast the enum to the int manually:

using System;
using System.Collecti ons;
using System.Collecti ons.Generic;

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

static void Main() {
// some demo data
Dictionary<Some Enum, stringdata = new
Dictionary<Some Enum,string>();
data.Add(SomeEn um.A, "a");
data.Add(SomeEn um.B, "b");
data.Add(SomeEn um.C, "c");
data.Add(SomeEn um.D, "d");
// convert using IDictionary
IDictionary idata = data; // non-typed interface to data
IDictionaryEnum erator enum1 = data.GetEnumera tor();
Dictionary<int, stringnewData = new Dictionary<int, string>();
while(enum1.Mov eNext()) {
newData.Add((in t)(SomeEnum)enu m1.Key, (string) enum1.Value);
}
// convert using IDictionary<T,T >
newData.Clear() ;
IDictionary<Som eEnum, stringgidata = data; // generic (typed)
interface to data
foreach(KeyValu ePair<SomeEnum, stringpair in gidata) {
newData.Add((in t) 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)boxed Enum;
int i2 = (int)boxedEnum;
}
}

The i1 works correctly while i2 fails with InvalidCastExce ption.

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 NullReferenceEx ception is thrown.
2. If the reference doesn't refer to an object that is boxed instance of
the desired value type, an InvalidCastExce ption 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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
5443
by: tshad | last post by:
The error I am getting is: ******************************************************************* Exception Details: System.InvalidCastException: Cast from type 'DBNull' to type 'String' is not valid. Source Error: Line 144: firstName.text = ClientReader("firstName") Line 145: lastName.text = ClientReader("lastName")
3
7081
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 = Server.CreateObject("ADODB.Recordset")". if (Request.QueryString("StudentID") <> "") then rsStudents__MMColParam = Request.QueryString("StudentID")
9
1941
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: sdist(i). The information is a string. When I run the application, I don"t have problem for compilation but during te execution, I have the error Cast from type 'Object()' to type 'String' is not valid on the line: sdistinguishedname = Sdist(i). Or...
5
1202
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 (InputVar) Is DataType Then Return CType(InputVar, Datatype) End If
0
9474
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10305
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10137
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10074
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9928
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8959
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7483
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.