Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Using "using"

Using "using"

Scheduled Pinned Locked Moved C#
question
26 Posts 13 Posters 3 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Pete OHanlon

    John using is a convenience that hides the following pattern:

    FileStream fs = null;
    try
    {
    fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
    }
    finally
    {
    ((IDisposable)fs).Dispose();
    }

    Basically, this guarantees that the Dispose method is called regardless of whether an exception happens or not, thus freeing up unmanaged resources in this case. If a class has a Dispose method, then it should always be called because (presumably) the developers have identified that particular items have to be freed up probably because they are expensive to maintain. The added bonus here is that most implementations of Dispose call GC.SuppressFinalize(...); so the finalizer (if any) is suppressed.

    Deja View - the feeling that you've seen this post before.

    My blog | My articles

    N Offline
    N Offline
    N a v a n e e t h
    wrote on last edited by
    #4

    Pete O'Hanlon wrote:

    ((IDisposable)fs).Dispose();

    Just wondering why this cast ? fs.Dispose() will do it, Right ?

    All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

    T 1 Reply Last reply
    0
    • realJSOPR realJSOP

      I've seen a lot of code that looks something like the following:

      using (using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))

      I realize that this ensures that everything will be properly closed and disposed without you having to do anything, but doesn't the same thing happen when the object goes out of scope? Further, what about exception handling? Is that automatically handled as well? Is it wrong to not want to sue this construct in favor of more obvious code?

      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
      -----
      "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

      L Offline
      L Offline
      led mike
      wrote on last edited by
      #5

      John Simmons / outlaw programmer wrote:

      but doesn't the same thing happen when the object goes out of scope?

      Yes but garbage collection is non-deterministic and using offers deterministic resource clean up. I'm just the messenger, don't shoot me!

      led mike

      R 1 Reply Last reply
      0
      • realJSOPR realJSOP

        I've seen a lot of code that looks something like the following:

        using (using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))

        I realize that this ensures that everything will be properly closed and disposed without you having to do anything, but doesn't the same thing happen when the object goes out of scope? Further, what about exception handling? Is that automatically handled as well? Is it wrong to not want to sue this construct in favor of more obvious code?

        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
        -----
        "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

        G Offline
        G Offline
        Guffa
        wrote on last edited by
        #6

        John Simmons / outlaw programmer wrote:

        I realize that this ensures that everything will be properly closed and disposed without you having to do anything, but doesn't the same thing happen when the object goes out of scope?

        No, it doesn't. The memory management doesn't use reference counting, which means that nothing happens because of an object going out of scope. Because there is no possibility to add any code that will run when the object goes out of scope, the IDisposable interface was created, so that the lifetime of an object could be controlled from the code. Ordinary objects that doesn't have a specific need for any cleanup, doesn't have a Dispose method. They will just be removed when the garbage collector notices that the can be.

        Despite everything, the person most likely to be fooling you next is yourself.

        R 1 Reply Last reply
        0
        • P Pete OHanlon

          John using is a convenience that hides the following pattern:

          FileStream fs = null;
          try
          {
          fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
          }
          finally
          {
          ((IDisposable)fs).Dispose();
          }

          Basically, this guarantees that the Dispose method is called regardless of whether an exception happens or not, thus freeing up unmanaged resources in this case. If a class has a Dispose method, then it should always be called because (presumably) the developers have identified that particular items have to be freed up probably because they are expensive to maintain. The added bonus here is that most implementations of Dispose call GC.SuppressFinalize(...); so the finalizer (if any) is suppressed.

          Deja View - the feeling that you've seen this post before.

          My blog | My articles

          S Offline
          S Offline
          S Senthil Kumar
          wrote on last edited by
          #7

          Nitpicking here, but you forgot if (fs != null) :). The finally block looks like

          if (fs != null)
          ((IDisposable)fs).Dispose();

          Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

          P 1 Reply Last reply
          0
          • P Pete OHanlon

            John using is a convenience that hides the following pattern:

            FileStream fs = null;
            try
            {
            fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            }
            finally
            {
            ((IDisposable)fs).Dispose();
            }

            Basically, this guarantees that the Dispose method is called regardless of whether an exception happens or not, thus freeing up unmanaged resources in this case. If a class has a Dispose method, then it should always be called because (presumably) the developers have identified that particular items have to be freed up probably because they are expensive to maintain. The added bonus here is that most implementations of Dispose call GC.SuppressFinalize(...); so the finalizer (if any) is suppressed.

            Deja View - the feeling that you've seen this post before.

            My blog | My articles

            L Offline
            L Offline
            led mike
            wrote on last edited by
            #8

            Pete O'Hanlon wrote:

            because (presumably) the developers have identified that particular items have to be freed up probably because they are expensive to maintain.

            Great. And isn't this very similar to responsibility for memory allocation and freeing that makes a Garbage Collection environment so desirable? :rolleyes:  I mean you'd think a VB developer that can actually understand the Dispose Pattern could handle new and delete. I'm just saying... :-\

            led mike

            1 Reply Last reply
            0
            • N N a v a n e e t h

              Pete O'Hanlon wrote:

              ((IDisposable)fs).Dispose();

              Just wondering why this cast ? fs.Dispose() will do it, Right ?

              All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

              T Offline
              T Offline
              tgrt
              wrote on last edited by
              #9

              The object will be freed, but any unmanaged resources will linger unless freed up. Implementing the IDisposable interface is the recommended way to do that. And as someone mentioned using is just a shorthand way to call it safely. Eventually the garbage collector will collect the object; however, that doesn't necessarily free resources. The finalizer will be called unless suppressed, but that will only call Dispose if you specifically do so in your finalizer code.

              N a v a n e e t h wrote:

              Just wondering why this cast ? fs.Dispose() will do it, Right ?

              The object may not directly implement the interface, but may have explictly implemented it. In that case its necessary to cast the object to IDisposable.

              C L 2 Replies Last reply
              0
              • realJSOPR realJSOP

                I've seen a lot of code that looks something like the following:

                using (using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))

                I realize that this ensures that everything will be properly closed and disposed without you having to do anything, but doesn't the same thing happen when the object goes out of scope? Further, what about exception handling? Is that automatically handled as well? Is it wrong to not want to sue this construct in favor of more obvious code?

                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                S Offline
                S Offline
                S Senthil Kumar
                wrote on last edited by
                #10

                John Simmons / outlaw programmer wrote:

                I realize that this ensures that everything will be properly closed and disposed without you having to do anything, but doesn't the same thing happen when the object goes out of scope?

                Not when the object goes out of scope, but when the GC runs and that too only if the object has a finalizer. Garbage collection cleans up the object itself; it doesn't attempt to clean up any resources held by the object. IDisposable (and the finalizer) do the resource cleanup part.

                Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                1 Reply Last reply
                0
                • T tgrt

                  The object will be freed, but any unmanaged resources will linger unless freed up. Implementing the IDisposable interface is the recommended way to do that. And as someone mentioned using is just a shorthand way to call it safely. Eventually the garbage collector will collect the object; however, that doesn't necessarily free resources. The finalizer will be called unless suppressed, but that will only call Dispose if you specifically do so in your finalizer code.

                  N a v a n e e t h wrote:

                  Just wondering why this cast ? fs.Dispose() will do it, Right ?

                  The object may not directly implement the interface, but may have explictly implemented it. In that case its necessary to cast the object to IDisposable.

                  C Offline
                  C Offline
                  Colin Angus Mackay
                  wrote on last edited by
                  #11

                  tgrt wrote:

                  The object may not directly implement the interface

                  Did you mean "implicitly"? Both implicit and explicit implimentations are direct, surely?

                  Upcoming FREE developer events: * Developer Day Scotland Recent blog posts: * Introduction to LINQ to XML (Part 1) - (Part 2) My website | Blog

                  T 1 Reply Last reply
                  0
                  • realJSOPR realJSOP

                    I've seen a lot of code that looks something like the following:

                    using (using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))

                    I realize that this ensures that everything will be properly closed and disposed without you having to do anything, but doesn't the same thing happen when the object goes out of scope? Further, what about exception handling? Is that automatically handled as well? Is it wrong to not want to sue this construct in favor of more obvious code?

                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                    D Offline
                    D Offline
                    DavidNohejl
                    wrote on last edited by
                    #12

                    See http://www.codeproject.com/KB/cs/tinguusingstatement.aspx[^]

                    John Simmons / outlaw programmer wrote:

                    Is it wrong to not want to sue this construct in favor of more obvious code?

                    Do you want to type out all the try-finally-dispose things again and again, or understand using once and save the typing (AND reading)? edit: omfg, it took me 30min to write this and find a link :~ there wasnt any replies when i started typing...


                    [My Blog]
                    "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
                    "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

                    P 1 Reply Last reply
                    0
                    • C Colin Angus Mackay

                      tgrt wrote:

                      The object may not directly implement the interface

                      Did you mean "implicitly"? Both implicit and explicit implimentations are direct, surely?

                      Upcoming FREE developer events: * Developer Day Scotland Recent blog posts: * Introduction to LINQ to XML (Part 1) - (Part 2) My website | Blog

                      T Offline
                      T Offline
                      tgrt
                      wrote on last edited by
                      #13

                      Yeah. I just don't like that word. I guess direct wasn't the best substitute.

                      1 Reply Last reply
                      0
                      • realJSOPR realJSOP

                        I've seen a lot of code that looks something like the following:

                        using (using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))

                        I realize that this ensures that everything will be properly closed and disposed without you having to do anything, but doesn't the same thing happen when the object goes out of scope? Further, what about exception handling? Is that automatically handled as well? Is it wrong to not want to sue this construct in favor of more obvious code?

                        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                        -----
                        "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #14

                        What's with the extra using ( ?

                        S 1 Reply Last reply
                        0
                        • L led mike

                          John Simmons / outlaw programmer wrote:

                          but doesn't the same thing happen when the object goes out of scope?

                          Yes but garbage collection is non-deterministic and using offers deterministic resource clean up. I'm just the messenger, don't shoot me!

                          led mike

                          R Offline
                          R Offline
                          Roger Alsing 0
                          wrote on last edited by
                          #15

                          GC and dispose are also doing different stuff. GC frees the memory allocated by the managed object. Dispose is supposed to release native resources allocated by an object. So even if you call dispose, the managed object is still present untill it gets eaten by the GC.

                          Blog: http://www.rogeralsing.com Projects: http://www.puzzleframework.com

                          1 Reply Last reply
                          0
                          • G Guffa

                            John Simmons / outlaw programmer wrote:

                            I realize that this ensures that everything will be properly closed and disposed without you having to do anything, but doesn't the same thing happen when the object goes out of scope?

                            No, it doesn't. The memory management doesn't use reference counting, which means that nothing happens because of an object going out of scope. Because there is no possibility to add any code that will run when the object goes out of scope, the IDisposable interface was created, so that the lifetime of an object could be controlled from the code. Ordinary objects that doesn't have a specific need for any cleanup, doesn't have a Dispose method. They will just be removed when the garbage collector notices that the can be.

                            Despite everything, the person most likely to be fooling you next is yourself.

                            R Offline
                            R Offline
                            Roger Alsing 0
                            wrote on last edited by
                            #16

                            >>so that the lifetime of an object could be controlled from the code. rather: Lifetime of resources used by an object could be controlled from the code. The disposable object itself will not be removed from memory when you call dispose on it..

                            Blog: http://www.rogeralsing.com Projects: http://www.puzzleframework.com

                            G 1 Reply Last reply
                            0
                            • S S Senthil Kumar

                              Nitpicking here, but you forgot if (fs != null) :). The finally block looks like

                              if (fs != null)
                              ((IDisposable)fs).Dispose();

                              Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                              P Offline
                              P Offline
                              Pete OHanlon
                              wrote on last edited by
                              #17

                              Spot on. Sorry and all that. ;)

                              Deja View - the feeling that you've seen this post before.

                              My blog | My articles

                              1 Reply Last reply
                              0
                              • D DavidNohejl

                                See http://www.codeproject.com/KB/cs/tinguusingstatement.aspx[^]

                                John Simmons / outlaw programmer wrote:

                                Is it wrong to not want to sue this construct in favor of more obvious code?

                                Do you want to type out all the try-finally-dispose things again and again, or understand using once and save the typing (AND reading)? edit: omfg, it took me 30min to write this and find a link :~ there wasnt any replies when i started typing...


                                [My Blog]
                                "Visual studio desperately needs some performance improvements. It is sometimes almost as slow as eclipse." - Rüdiger Klaehn
                                "Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

                                P Offline
                                P Offline
                                Pete OHanlon
                                wrote on last edited by
                                #18

                                dnh wrote:

                                edit: omfg, it took me 30min to write this and find a link there wasnt any replies when i started typing...

                                Sorry - I just typed my answer from memory which was why I missed a null check. ;)

                                Deja View - the feeling that you've seen this post before.

                                My blog | My articles

                                1 Reply Last reply
                                0
                                • R Roger Alsing 0

                                  >>so that the lifetime of an object could be controlled from the code. rather: Lifetime of resources used by an object could be controlled from the code. The disposable object itself will not be removed from memory when you call dispose on it..

                                  Blog: http://www.rogeralsing.com Projects: http://www.puzzleframework.com

                                  G Offline
                                  G Offline
                                  Guffa
                                  wrote on last edited by
                                  #19

                                  Roger Alsing wrote:

                                  rather: Lifetime of resources used by an object could be controlled from the code.

                                  Good point. I should have said that it's for controlling the life cycle of the object rather than the lifetime.

                                  Despite everything, the person most likely to be fooling you next is yourself.

                                  1 Reply Last reply
                                  0
                                  • P PIEBALDconsult

                                    What's with the extra using ( ?

                                    S Offline
                                    S Offline
                                    Spacix One
                                    wrote on last edited by
                                    #20

                                    Wasn't this the OP's question?


                                    -Spacix All your skynet questions[^] belong to solved


                                    I dislike the black-and-white voting system on questions/answers. X|


                                    P 1 Reply Last reply
                                    0
                                    • S Spacix One

                                      Wasn't this the OP's question?


                                      -Spacix All your skynet questions[^] belong to solved


                                      I dislike the black-and-white voting system on questions/answers. X|


                                      P Offline
                                      P Offline
                                      PIEBALDconsult
                                      wrote on last edited by
                                      #21

                                      I can't tell.

                                      1 Reply Last reply
                                      0
                                      • P Pete OHanlon

                                        John using is a convenience that hides the following pattern:

                                        FileStream fs = null;
                                        try
                                        {
                                        fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
                                        }
                                        finally
                                        {
                                        ((IDisposable)fs).Dispose();
                                        }

                                        Basically, this guarantees that the Dispose method is called regardless of whether an exception happens or not, thus freeing up unmanaged resources in this case. If a class has a Dispose method, then it should always be called because (presumably) the developers have identified that particular items have to be freed up probably because they are expensive to maintain. The added bonus here is that most implementations of Dispose call GC.SuppressFinalize(...); so the finalizer (if any) is suppressed.

                                        Deja View - the feeling that you've seen this post before.

                                        My blog | My articles

                                        realJSOPR Offline
                                        realJSOPR Offline
                                        realJSOP
                                        wrote on last edited by
                                        #22

                                        I don't call dispose on streams, but I do call close(). Isn't that the same thing?

                                        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                        -----
                                        "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                        P S 2 Replies Last reply
                                        0
                                        • T tgrt

                                          The object will be freed, but any unmanaged resources will linger unless freed up. Implementing the IDisposable interface is the recommended way to do that. And as someone mentioned using is just a shorthand way to call it safely. Eventually the garbage collector will collect the object; however, that doesn't necessarily free resources. The finalizer will be called unless suppressed, but that will only call Dispose if you specifically do so in your finalizer code.

                                          N a v a n e e t h wrote:

                                          Just wondering why this cast ? fs.Dispose() will do it, Right ?

                                          The object may not directly implement the interface, but may have explictly implemented it. In that case its necessary to cast the object to IDisposable.

                                          L Offline
                                          L Offline
                                          LongRange Shooter
                                          wrote on last edited by
                                          #23

                                          >>Eventually the garbage collector will collect the object; however, that doesn't necessarily free resources. The finalizer will be called unless suppressed, but that will only call Dispose if you specifically do so in your finalizer code.<< The using command, especially when applied to IO resources, is more complex than just calling Dispose. For example take this segment of code:

                                           using ( FileStream list = Text.OpenWrite( path ) )
                                           {
                                                    foreach ( UniqueObject item in myArrayOfObject )
                                                    {
                                                         list.Write( UniqueObject.Message, UniqueObject.GetAverage() );
                                                    }
                                           }
                                          

                                          When you exit the using block, three things will happen. The buffer will be flushed, the file will be closed, and the object will be disposed of. Likewise (and more importantly) if UniqueObject.GetAverage() blew a divide by zero exception your code would leave this execution block. When that happens....using will flush the buffer, close the file, dispose of the object. This process first and formost protects long-running application from creating memory leaks leaving these streams and rare resources around. Secondly it ensures that any unmanaged resources (like file handles) are released. Finally it ensures that even an exception will not cause your file to get corrupted by early interuptus.

                                          P 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups