473,729 Members | 1,914 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting problem with small int

When using a DataReader to return records from a SQL server, I'm having a
problem with the following code (abbreviated)

int ID = 0;
ID = (int)dr["user_id"];

will work if the user_id column is an int field. The same code throws an
invalid cast exception if the user_id column is a smallint. To fix the
problem, this code works:

int ID = 0;
ID = (int)(smallint) dr["user_id"];

I can also use:

ID = dr.GetInt16(0);

but that's not as immediately obvious to someone that is looking at my code.

The double cast seems kind of hokey......what 's the proper way to make this
assignment?
Jan 14 '06 #1
6 20112

What about something like:

int ID = Int32.Parse(dr["user_id"]);

?

Jan 14 '06 #2
"Chris Malone" wrote:

What about something like:

int ID = Int32.Parse(dr["user_id"]);

?

Int32.Parse() is expecting a string parameter, dr["user_id"] is of type
'object'. I can use:

Int32.Parse(dr["user_id"].ToString())

but this seems to be a pretty complex conversion to cast a 'smallint' to an
'int'.

Surely there's a better way.
Jan 14 '06 #3
Mike,
look over the documentation for the DataReader class. It has many methods
such as GetInteger, etc.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Mike" wrote:
"Chris Malone" wrote:

What about something like:

int ID = Int32.Parse(dr["user_id"]);

?

Int32.Parse() is expecting a string parameter, dr["user_id"] is of type
'object'. I can use:

Int32.Parse(dr["user_id"].ToString())

but this seems to be a pretty complex conversion to cast a 'smallint' to an
'int'.

Surely there's a better way.

Jan 14 '06 #4
Thanks, guess I'm going with:

ID = (int)dr.GetInt1 6(0);

or

ID = dr["user_id"] is DBNull ? 0 : (int)dr.GetInt1 6(0);

Still seems like I shouldn't have to explicitly cast and Int16 to an Int32
(int)....
Jan 14 '06 #5
Mike <Mi**@discussio ns.microsoft.co m> wrote:
Thanks, guess I'm going with:

ID = (int)dr.GetInt1 6(0);

or

ID = dr["user_id"] is DBNull ? 0 : (int)dr.GetInt1 6(0);

Still seems like I shouldn't have to explicitly cast and Int16 to an Int32
(int)....


You don't need to cast if you call dr.GetInt16(0), because that returns
a short which is implicitly convertible to int. You only need to cast
to short if you just use the indexer. That's because it's actually
doing unboxing, which requires exactly the right type (modulo enums).
You should be able to do:

ID = (short) dr["user_id"];

--
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
Jan 14 '06 #6
Thanks for the help guys, the problem wasn't with the cast, but trying to use
the ternary operator:

ID = dr["user_id"] is DBNull ? 0 : (short)dr["user_id"];

This does not work becuase you must be able to convert both sides of the :
operator. So this...

ID = dr["user_id"] is DBNull ? (short)0 : (short)dr["user_id"];

....does work since both sides of the : operator are of type 'short'. You
learn something new every day. Thanks for steering me in the right direction
guys.

Jan 14 '06 #7

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

Similar topics

7
1427
by: Cybertof | last post by:
Hello, In the code below, is there a shortcut not to use the temp var CurrEmployee ? I would like to use something like "if (Employee)MyArrayList.Name" but don't know the syntax....
17
2948
by: David Sobey | last post by:
hi - I have a class Node, with a child class Num, that inherits from Node. - I have a function "Evaluate" that takes two Nodes as an argument. - I call this function by sending it two "Num"'s. When i use GetType().ToSTring(), it seems to be aware that the arguments it recieved are in fact Nums, not Nodes. - How do I cast the arguments to Nums so I can use all the member functions and variables, without doing
2
2896
by: rajivpopat | last post by:
I've been reading a discussion thread at http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_frm/thread/119f8362a9f5ff52 regarding typecasting generic collections to classical collections and vice-a-versa I faced a similar problem and solved it slightly differently... The apporach i seems to work but i am sure someone has a better apporach for solving this problem. In my case i was using nHibernate which was...
6
1629
by: kalyan.listsubs | last post by:
Hi, I have the below program which will simply write struct employee to a file (binary mode). The problem here is empid is writen to the file but the name (char name) is not written. I am using cygwin (gcc compiler) and use the following commands to compile & run respectively: gcc -o emp emp.c ../emp write -> this will create a file emp.out and write employee (Adam
2
2576
by: srikar | last post by:
Hi all, When I type cast an int value with (void*) I am able to get the value represented in hex format. But in 64 bit I cant convert int value in to (void*) to obtain the value in hex format Is there any method which can help me Regards srikar
8
2743
by: manmit.walia | last post by:
Hello Everyone, Long time ago, I posted a small problem I had about converting a VB6 program to C#. Well with the help with everyone I got it converted. But I overlooked something and don't understand why it is doing this. Below is my code, I would be greatfull if someone can guide me through the right path or even help me solve this issue. Problem: The old tool which was written in VB6 works perfect. But I needed to convert this to C#...
8
1423
by: buzzweetman | last post by:
Can someone explain this: void Test() { short x = 10; float y = 9.9f; float a = (float)x; a *= y; short b = (short)a; // I get 99. Good!
0
8932
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8767
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
9295
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...
0
9163
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...
1
6722
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...
0
6028
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4799
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2702
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2173
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.