Why
You can only delete the value type in its original type. In your cast case, you first need to switch to long from object , and then to ulong .
See this question for more details:
Why can't I unzip int as decimal?
He also links a blog post from Eric Lippert.
how
One way, as you know, is to discard the original type before making it to T - unless, of course, the original type is T
As mentioned in the comments, another way is to use conversion procedures ( Convert.ToUInt64 ) and not explicit casting.
This can be achieved using Func<object, T> :
public static T ExecuteScalar<T>( Func<object, T> conversionFunctor, string query, SqlConnection connection, params SqlParameter[] parameters) where T : new() { // Create SqlCommand SqlCommand command = CreateCommand(query, connection, parameters); // Execute command using ExecuteScalar object result = command.ExecuteScalar(); // Return value as expected type if (result == null || result is DBNull) return default(T); return conversionFunctor(result); }
Making a call:
ulong minActiveRowversion = SqlUtils.ExecuteScalar<ulong>( Convert.ToUInt64, "SELECT CAST(MIN_ACTIVE_ROWVERSION() AS BIGINT)" , _connectionString);
Adam houldsworth
source share