Monday, September 11, 2017

Using

Using .Net.  No, I am not referring to drug that I am using called .NET, but the Using statement in the .NET framework.  The “Using” statement in .NET framework provides a convenient syntax that ensures the correct use of IDisposable objects.

If .NET object you are using implements IDisposable, then you can simply call the Dispose method your self

    ReportDocument report = new ReportDocument();

    // do something with the report

    report.Close();
    report.Dispose();

But what if an exception happens when you are doing something with the report? The .Close and .Dispose methods will never be called.

Or you could also use a Try Catch block, and in the catch perform the .Close and .Dispose

    ReportDocument report = new ReportDocument();

    try
    {
        // do something with the report

    }
    catch (Exception)
    {
        report.Close();
        report.Dispose();

        throw;
    }

But this does become verbose and it requires you to remember the try/catch and add the close and/or dispose methods.

Now, with the Using statement, it looks like this.

    using (ReportDocument report = new ReportDocument())
    {
        // do something with the report
    }

This Using block, will instantiate the report object, and when you are done doing something with that report object, it will properly dispose of the object, and IF the object has a .close method, the Dispose method will perform the Close and then Dispose.  Now... depending on your object and what you are doing with the "do something here", you may still want to put this Using inside a Try/Catch.

You can also nest Using statements. Below is an example of this, and putting it all in a Try/Catch block.

    try
    {
        using (DataSet ds = new DataSet())
        using (SqlConnection sqlConnection = GetWebOrdersConnection())
        using (SqlDataAdapter da = new SqlDataAdapter(sql, sqlConnection))
        {
            da.Fill(ds, "MyTable");
            if (ds.Tables[0].Rows.Count == 1)
            {
                result = true;
            }
        }
    }
    catch (Exception)
    {
        throw;
    }

In VB.Net it is a bit more verbose, but it all works the same. Below is an example in VB.Net, with out the Try/Catch.

    Using ds As New System.Data.DataSet
        Using conn As System.Data.SqlClient.SqlConnection = WebOrdersService.GetWebOrdersConnection
            Using da As New System.Data.SqlClient.SqlDataAdapter(wrksqlstm, conn)
                da.Fill(ds, "Apps")
            End Using
        End Using
    End Using



No comments:

Post a Comment