3

I have read somewhere on this site or CodeProject that good rule is if some class has implemented IDisposable interface than and only than you should use using keyword because using keyword translated into MSIL is try/finally block something like this:

try
{
   //some logic 
}
finally
{
   if (obj != null)
      {
         obj.Dispose();
      }
}

but while watching tutorials for Entity Framework, I came across something like this:

using(SampleBEntities db = new SampleBEntities()){//some logic here} 

and SampleBEntities inherits from ObjectContext and in the MSDN lib ObjectContext does not implement the IDisposable?

2
  • If it didn't implement IDisposable, the code wouldn't compile. Commented Jul 3, 2012 at 18:33
  • post your MSDN link from where you learned ObjectContext does not implement the IDisposable? Commented Jul 3, 2012 at 18:34

1 Answer 1

6

Yes it does implement IDisposable interface.

public class ObjectContext : IDisposable

Check MSDN

It has methods Dispose() which comes from implementing IDisposable interface.

If it did not implement as you stated leave alone running, it won't even compile.

using statements

Using defines a scope, outside of which an object or objects will be disposed.

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection.

The using statement allows us to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.