Skip to main content
malachi comment
Source Link
Paritosh
  • 2.6k
  • 18
  • 26

Just continuation to @Malachi an here is a generic version of ExecuteScalar,

so it is good so you dont have to cast it again in code.

   private T ExecuteScalar<T>(long index)
    {
        using (var connection= new SqlConnection("YourConnectionString"))
        {
            using (var command = new SqlCommand(commandText, connection))
            {
                var output = command.ExecuteScalar();
                if (output != null)
                {
                    return (T)Convert.ChangeType(output, typeof(T), CultureInfo.InvariantCulture);
                }
                return default(T);
            }  
        }
    }

Just continuation to @Malachi an here is a generic version of ExecuteScalar,

so it is good so you dont have to cast it again in code.

   private T ExecuteScalar<T>(long index)
    {
        using (var connection= new SqlConnection("YourConnectionString"))
        {
            using (var command = new SqlCommand(commandText, connection))
            {
                var output = command.ExecuteScalar();
                if (output != null)
                {
                    return (T)Convert.ChangeType(output, typeof(T), CultureInfo.InvariantCulture);
                }
                return default(T);
            }  
        }
    }

Just continuation to @Malachi an here is a generic version of ExecuteScalar,

so it is good so you dont have to cast it again in code.

private T ExecuteScalar<T>(long index)
{
    using (var command = new SqlCommand(commandText, connection))
    {
        var output = command.ExecuteScalar();
        if (output != null)
        {
            return (T)Convert.ChangeType(output, typeof(T), CultureInfo.InvariantCulture);
        }
        return default(T);
    } 
}
Source Link
Paritosh
  • 2.6k
  • 18
  • 26

Just continuation to @Malachi an here is a generic version of ExecuteScalar,

so it is good so you dont have to cast it again in code.

   private T ExecuteScalar<T>(long index)
    {
        using (var connection= new SqlConnection("YourConnectionString"))
        {
            using (var command = new SqlCommand(commandText, connection))
            {
                var output = command.ExecuteScalar();
                if (output != null)
                {
                    return (T)Convert.ChangeType(output, typeof(T), CultureInfo.InvariantCulture);
                }
                return default(T);
            }  
        }
    }