Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hey friends,

Just a small question about type conversions. What is the best way to convert an object to an integer?

For example, if I retrieve an integer from SQL Server using a Stored Procedure, I use the SqlCommand's ExecuteScalar() method :

object spResult = SqlCommand.ExecuteScalar();


Now i'm (pretty) sure that the spResult variable either is null or contains an integer since my Stored Procedure returns a single int field from my datasource.

If I want to convert the spResult to an int I either use int.Parse(spResult.ToString()); or int.TryParse(spResult.ToString(), out resultInteger); but I have a feeling that this is not the neat way.

What do you guys think?

Thanks! Eduard
Posted

If the spResult can contain either null or of type Int, then i would prefer to use
Nullable<int>


Here is the link : http://www.jaltiere.com/index.php/2006/07/24/net-nullable-data-types/[^]
 
Share this answer
 
v4
Comments
Tarun.K.S 18-Mar-11 8:32am    
I mean ignore the second int!
Eduard Keilholz 18-Mar-11 8:39am    
(removed it ;-)
Tarun.K.S 18-Mar-11 8:40am    
Lol thanks!
There's:

C#
int value = (int)spResult;
int value = spResult as Int32;
int value = Convert.ToInt32(spResult);

If you're not sure you're going to get an int from the method, you should use

C#
int value;
if (!int.TryParse(spResult, out value))
{
    throw new Exception("Not an int");   
    return;
}
 
Share this answer
 
v2
Comments
Eduard Keilholz 18-Mar-11 8:34am    
Thanks for your response! However, int.TryParse does not accept an object.
Problem is thet both int.Parse and int.TryParse only accept strings, so I need to convert the object to a string first.
I'm really not sure what's better. I've used this in the past:

C#
int spResult = SqlCommand.ExecuteScalar() as int;


MSDN on the other hand uses a cast like this:

int spResult = (int)SqlCommand.ExecuteScalar();


http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx[^]
 
Share this answer
 
Comments
Eduard Keilholz 18-Mar-11 8:32am    
Will the MSDN method not throw an exception when the ExecuteScalar method returns null?

The first method does not work since the conversion must be able to return a nullable type. Than this would be a better solution :

Nullable<int> spResult = SqlCommand.ExecuteScalar() as Nullable<int>;
int resultInteger = (spResult.HasValue) ? spResult.Value : -1;
Tarun.K.S 18-Mar-11 8:38am    
So my answer worked right?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900