I've got some data access layer code calls a stored proc and returns scalar values of various datatypes. The syntax is ExecuteDecimal, ExecuteString, etc. I want it to be Execute<string>
or Execute<decimal>
I try this implementation and I can't compile, unless I'm doing casting using "(T) value", if I try to check the type and call a method to do the casting, no such luck.
UPDATED question Why do I have to convert to object before converting to T?
UPDATED code
internal T Execute<T>(string storedProcName, Hashtable parameters)
{
//Next lines do compile (thanks to suggestions from answers!)
if (typeof(T) == typeof(string))
return (T) (object) ExecuteScalar(storedProcName, parameters).ToString();
else if (typeof(T) == typeof(int))
return (T)(object) Convert.ToInt32(ExecuteScalar(storedProcName, parameters));
//Next line compiles, but not all things boxed in an object can
//be converted straight to type T (esp db return values that might contain DbNull.Value, etc)
return (T)ExecuteScalar(storedProcName, parameters);
}