What does this statement means in C#?
using (object obj = new object())
{
//random stuff
}
What does this statement means in C#?
using (object obj = new object())
{
//random stuff
}
It means that obj
implements IDisposible
and will be properly disposed of after the using
block. It's functionally the same as:
{
//Assumes SomeObject implements IDisposable
SomeObject obj = new SomeObject();
try
{
// Do more stuff here.
}
finally
{
if (obj != null)
{
((IDisposable)obj).Dispose();
}
}
}
using (object obj = new object())
{
//random stuff
}
Is equivalent to:
object obj = new object();
try
{
// random stuff
}
finally {
((IDisposable)obj).Dispose();
}
it is a way to scope an object so the dispose method is called on exit. It is very useful for database connections in particuler. a compile time error will occur if the object does not implement idisposable
using
ensures the allocated object is properly disposed after the using block, even when an unhandled exception occurs in the block.
why does it exist tho.
It exists for classes where you care about their lifetime, in particular where the class wraps a resource in the OS and you want to release it immediately. Otherwise you would have to wait for the CLR's (non deterministic) finalizers.
Examples, file handles, DB connections, socket connections, ....