0

I have the following code:

        try
        {
            using (var context = new DataContext())
            {
                if (!context.Database.Exists())
                {
                    // Create the SimpleMembership database without Entity Framework migration schema
                    ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                }
            }


            WebSecurity.InitializeDatabaseConnection("xxx", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            var sql = System.IO.File.ReadAllText("SqlScript.sql");
            context.Database.ExecuteSqlCommand(sql);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
        }

Can someone explain what the purpose of the "using" is ?

  • Outside using your variables are getting disposed. Meaning you do not need to explicitly close FileStreams, Database Connections, etc. – Alina B. Mar 10 '13 at 13:58
  • 4
    What have you not understood in the [**manual**](http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.100).aspx)? – Tim Schmelter Mar 10 '13 at 13:58

5 Answers5

3

It is syntactic sugar for a proper disposal pattern.

It is equivalent to

DataContext context = new DataContext();
try
{
   // using context here
}
finally
{
  if(context != null)
    ((IDisposable)context).Dispose();
}

This is described in the MSDN article for using Statement.

Using using in this way ensures proper disposable and reduces chances of programmer mistakes.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

using automatically dispose the object after it has been used. You don't need to manually call .Dispose().

using (var context = new DataContext())
{
    // other codes
}  
// at this point the context is already disposed

is the same as

var context = new DataContext()
// other codes
context.Dispose()    // manually calling Dispose()
// at this point the context is already disposed
John Woo
  • 258,903
  • 69
  • 498
  • 492
0

using statement ensures that Dispose is called at the end of using block. Your code is equivalent to:

var context = new DataContext();

try
{ 
   if (!context.Database.Exists())
   {
       ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
   }
}
finally
{
    if (context != null)
        context.Dispose();
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

The reason for the "using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens.

The using statement simplifies the code that you have to write to create and then finally clean up the object.

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

Is equivalent to:

MyResource myRes= new MyResource();
try
{
    myRes.DoSomething();
}
finally
{
    // Check for a null resource.
    if (myRes!= null)
        // Call the object's Dispose method.
        ((IDisposable)myRes).Dispose();
}
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
0

The keyword using is used for objects which implement the IDisposable Interface - they are containing unmanaged resources which would not be cleared, if the object was collected by the garbage collector.
When using using you limit the scope of the object to the curly braces and when the using-Statement is left, all unmanaged resources are disposed of.

See this article here.

bash.d
  • 13,029
  • 3
  • 29
  • 42