65.9K
CodeProject is changing. Read more.
Home

Converting a nullable object to an integer

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (10 votes)

Mar 18, 2011

CPOL
viewsIcon

46720

Type conversion

I decided to write this tip/trick because my question[^] on the CodeProject's questions[^] forum lead to quite some different thoughts. How do we convert objects to integers?
int convertedInteger;
object someValue; // Can be anything

// The conversion
Nullable<int> converted = someValue as Nullable<int>
// Or shorter
int? converted = someValue as int?;

convertedInteger = (converted.HasValue) ? converted.Value : -1;
So for example, if you execute a Microsoft SQL Stored Procedure of which you are sure it returns an integer (or of course a null value), the best way is to use the returned value:
int storedProcedureResult = -1; // Default value is -1

using (SqlCommand cmdMatch = new SqlCommand("spName", Connection))
{
  cmdMatch.CommandType = System.Data.CommandType.StoredProcedure;
  int? result = cmdMatch.ExecuteScalar() as int?;
  storedProcedureResult = (result.HasValue) ? result.Value : -1;
}
Some improvements to the code above (thanks to AspDotNetDev[^] who added an alternate):
int storedProcedureResult = -1; // Default value = -1

using (SqlCommand cmdMatch = new SqlCommand("spName", Connection))
{
  cmdMatch.CommandType = System.Data.CommandType.StoredProcedure;
  var converted = cmdMatch.ExecuteScalar() as int?;
  int storedProcedureResult = converted ?? -1;
}
It may have been obvious to all you guys, but I struggled having to convert the returned object first to a string in order to use int.Parse() and int.TryParse():

// This block is marked red because this is NOT the correct way
int storedProcedureResult = -1; // Default value is -1

using (SqlCommand cmdMatch = new SqlCommand("spName", Connection))
{

  cmdMatch.CommandType = System.Data.CommandType.StoredProcedure;
  object result = cmdMatch.ExecuteScalar();
  if (result != null)
  {
    int.TryParse(result.ToString(), out storedProcedureResult);
  }
}
Now we all know the neat way. ;)