Generic ExecuteScalar method
Just wanted to share with everyone the generic helper method I use for ExecuteScalar. A helper method for ExecuteScalar is the perfect candidate for generics due to the different types that could be returned. Of course, you could always return an object, but this is more fun. :)
public
static
T ExecuteScalar(
string
commandText,
string
connectionString)
{
return
ExecuteScalar(commandText, connectionString,
null
);
}
public
static
T ExecuteScalar(
string
commandText,
string
connectionString,
params
SqlParameter
[] parameters)
{
T result =
default
(T);
if
(!
string
.IsNullOrEmpty(commandText))
{
using
(
SqlConnection
connection =
new
SqlConnection
(connectionString))
{
using
(
SqlCommand
command =
new
SqlCommand
(commandText, connection))
{
if
(parameters !=
null
&& parameters.Length > 0)
{
foreach
(
SqlParameter
parameter
in
parameters)
{
command.Parameters.Add(parameter);
}
}
connection.Open();
result = (T)command.ExecuteScalar();
connection.Close();
}
}
}
return
result;
}