I have the following function:
public T GetScalar<T>(string sql, T defaultValue, SQLParam[] sqlParams = null)
{
DataTable dt = GetDataTable(sql, sqlParams);
if (dt.Rows.Count == 0) return defaultValue;
else
{
try
{
object tmp = dt.Rows[0][0];
return (T)tmp;
}
catch { return defaultValue; }
}
}
I am getting an InvalidCastException.
During debugging, I can see the value of tmp is 3, and T is of type int.
What is the problem here?
EDIT
A bit of background: This used to work in MySQL. I have now moved to SQLServer (with little effort thankfully) but this code now fails.
I suspect the value is actually a
long, or something like that – and when you unbox, you have to unbox to the exact type (there are a few oddities around signedness and enums, but notlongvsint).You should be able to see this if you put a watch on
tmp.GetType()– or just work out what type it should be from the SQL.