65.9K
CodeProject is changing. Read more.
Home

Method call in Using block TIP

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Nov 22, 2011

LGPL3
viewsIcon

10152

Method call in Using block TIP

Further to my first post here, today I noticed something cool with respect to Using blocks in C#. We all know that in using block, usually we create a type which implements IDisposable as shown below:

public class MyClass : IDisposable
   {
       public void Dispose()
       {
           Console.WriteLine("Disposed");
       }
   }

And the usage code looks like:

using (MyClass m = new MyClass()) { }

In fact, all these days, I have been doing the same w.r.t. using() blocks in all my code. But today I learned (yes, a real shame) that you need not always create a type, rather call a method in it actually. Let me show you a code on the same:

public class MyClass : IDisposable
   {
       public void Dispose()
       {
           Console.WriteLine("Disposed");
       }
   }

   public class UsingClass
   {
       public static MyClass SomeMethod()
       {
           return new MyClass();
       }
   }

    public partial class Program
    {        
        public static void Main()
        {
            using (UsingClass.SomeMethod()){ }

            Console.ReadLine();
        }    
    }

Here, the compiler has gone a bit smart because it efficiently sees that the return type of the method SomeMethod() is returning a type which implements IDisposable, hence it does not issue any error. Just remove the type implementing IDisposable, then you would get error.

Your comments are welcome. :)

Happy coding.


Filed under: C#, CodeProject, Dotnet Tagged: .NET, blog, C#, codeproject, Dotnet, tips