November 27, 2013

When a new instance of the object context class is created, it should be created using the using statement. It's because, in .NET, when a variable goes out of scope - the garbage collector retrieves its memory at its own time. The ObjectContext class holds resources including database connections which should be released when done. To achieve this, the using statement should be used. When the using code block is completed, the Dispose() method is called that closes the database connection and releases memory from all other unused objects from the using code block.

Do not use
  1. PersonEntities context = new PersonEntities();
  2. foreach (var person in context.People)
  3. {
  4.     System.Console.WriteLine("{0} {1}, Address: {2}",
  5.     person.FirstName, person.LastName, person.Address);
  6. }

 

Use following
  1. using (var context = new PersonEntities())
  2. {
  3.     foreach (var person in context.People)
  4.     {
  5.         System.Console.WriteLine("{0} {1}, Address: {2}",
  6.         person.FirstName, person.LastName, person.Address);
  7.     }
  8. }

Reference: Shahed Kazi at AspNetify.com