Search code examples
c#asp.netusing-statement

Do I need to use multiple using statements?


Both classes for practicality sake are disposable.

I understand what a using block does. But I'm not sure of all of the ways it can or needs to be used.

For example is this correct?

using (MyClass myClass = new MyClass(params))
{
     myClass.name = "Steve";

     SecondClass myClassSecond = new SecondClass(params);
     myClassSecond.name = "George";
     myClassSecond.msg = "Hello Man in the Yellow Hat";
}

Are both classes above disposed of?

Or do I need both inside a using statement?

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";
     }
}

Is the above correct, or is there a better way to use multiple using statements?


Solution

    • 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";
         }
    }