- The
using
statement allows the programmer 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.
Here is the sample showing use of using statement:
using System;
//Object of this class will be given to using hence IDisposable
class C : IDisposable
{
public void UseLimitedResource()
{
Console.WriteLine("Using limited resource...");
}
//Dispose() Method
void IDisposable.Dispose()
{
Console.WriteLine("Disposing limited resource.");
}
}
class Program
{
static void Main()
{
using (C c = new C()) //Object of Class defined above
{
c.UseLimitedResource();
//Object automatically disposed before closing.
}
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}
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.
Which is proper method?
As you are saying that
Both classes for practicality sake are disposable
., then your second approach is the appropriate one. that is:
using (MyClass myClass = new MyClass(params))
{
myClass.name = "Steve";
using (SecondClass myClassSecond = new SecondClass(params))
{
myClassSecond.name = "George";
myClassSecond.msg = "Hello Man in the Yellow Hat";
}
}