Click here to Skip to main content
15,886,806 members
Articles / Programming Languages / C#

Method call in Using block TIP

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
22 Nov 2011LGPL3 10.1K  
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:

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

And the usage code looks like:

C#
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:

C#
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

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Software Developer (Senior) Siemens
India India
A .net developer since 4+ years, wild, curious and adventurous nerd.

Loves Trekking/Hiking, animals and nature.

A FOSS/Linux maniac by default Wink | ;)

An MVP aspirant and loves blogging -> https://adventurouszen.wordpress.com/

Comments and Discussions

 
-- There are no messages in this forum --