I have a function to execute a query and return a scalar value like this:
public T GetScalarValue<T>(string sql)
{
T t;
try {
SqlConnection conn = new SqlConnection("MY_SQL_SERVER_CONNECTION_STRING");
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
t = (T)cmd.ExecuteScalar();
}
catch (Exception ex) {
throw ex;
}
finally{
if(conn.State == ConnectionState.Open)
conn.Close();
}
return t;
}
When I call this function with the given SQL, I’ll get the result:
int result = dal.GetScalarValue<int>("SELECT [schema_id] FROM SYS.SCHEMAS WHERE [name] = 'dbo'")
Since the query returns an int value this works fine, but when I call the same for the query which returns nothing my function will fail:
int result = dal.GetScalarValue<int>("SELECT [schema_id] FROM SYS.SCHEMAS WHERE [name] = 'Foooo'")
Since cmd.ExecuteScalar() returns no result,it will give “Object reference not set to an instance of an object” exception. But I want this function to return the default value for given Type (example: for int it should return 0, decimal- 0.00,for string – an empty value, for datetime – ‘1900-01-01’, etc.).
If you find better solution for this please let me know.
Thanks in advance for the help.
Try something like this:
Here I’m setting
resultto be the default value of the typeT. Next, if there is an exception then I just returnresultthere and then. So, in your failing example, the value 0 will be returned.EDIT:
A good point was raised in the comments. In the exception handler I’ve given you, I’m just returning the
result. It would be better to log, or somehow make note, of the exception so that you know whether something has gone wrong. One idea would be to log the exception using, say, a logger likeNLogorLog4Net– there’s plenty of choice.