IDbConnection - EnsureOpen

An IDbConnection extension method that ensures that open.

Try it

public static void Main()
{
	
	using (var conn = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
    {
        ConnectionState result1 = conn.State;
		
		//C# Extension Method: IDbConnection - EnsureOpen
        conn.EnsureOpen();
        ConnectionState result2 = conn.State;
		
		//C# Extension Method: IDbConnection - EnsureOpen
        conn.EnsureOpen();
        ConnectionState result3 = conn.State;
		
		Console.WriteLine(result1);
		Console.WriteLine(result2);
		Console.WriteLine(result3);
    }
}

View Source
using System.Data;

public static partial class Extensions
{
    /// <summary>
    ///     An IDbConnection extension method that ensures that open.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    public static void EnsureOpen(this IDbConnection @this)
    {
        if (@this.State == ConnectionState.Closed)
        {
            @this.Open();
        }
    }
}