DbCommand - ExecuteScalarAs

A DbCommand extension method that executes the scalar as operation.

Try it

public static void Main()
{
    const string sql = @"SELECT 1 As IntColumn";

    using (var conn = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
    {
        using (SqlCommand command = conn.CreateCommand())
        {
            conn.Open();
            command.CommandText = sql;
			
			//C# Extension Method: DbCommand - ExecuteScalarAs
            var result = command.ExecuteScalarAs<int>();

            Console.WriteLine(result);
        }
    }
}

View Source
using System.Data.Common;

public static partial class Extensions
{
    /// <summary>
    ///     A DbCommand extension method that executes the scalar as operation.
    /// </summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <returns>A T.</returns>
    public static T ExecuteScalarAs<T>(this DbCommand @this)
    {
        return (T) @this.ExecuteScalar();
    }
}