Click here to Skip to main content
12,629,188 members (34,213 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

8.7K views
Posted

Method call in Using block TIP

, 22 Nov 2011 LGPL3
Rate this:
Please Sign up or sign in to vote.
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

License

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

Share

About the Author

zenwalker1985
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/

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161205.3 | Last Updated 22 Nov 2011
Article Copyright 2011 by zenwalker1985
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid