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?
Yes it does implement
IDisposableinterface.Check MSDN
It has methods
Dispose()which comes from implementingIDisposableinterface.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.