CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2010
    Posts
    6

    IDispose Best Practices...

    I've searched for info, but I'm still confused. What is the best practice for Dispose() in this scenario and why?

    (And what are the code tags? doesn't seem to work.

    Code:
        class LineReader : ILineReader // derived from IDispose
        {
            StreamReader _file;
            bool _eof = false;
    
            public LineReader(ref string fileName)
            {
                _file = new StreamReader(fileName);
            }
    
            // Interface implementation
            public bool AtEof { get { return _eof; } }
    
            public String ReadNextLine()
            {
                string line = null;
    
                try
                {
                    if (_file.Peek() >= 0)
                    {
                        line = _file.ReadLine();
                    }
                    else
                    {
                        _eof = true;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("ReadNextLine() exception: " + e.Message);
                }
    
                return line;
            }
    
            // For IDisposable
            public void Dispose()
            {
                // What is best practice?
            }
        }

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: IDispose Best Practices...

    You can read up on it by searching bing or google for "Idisposable pattern msdn".

    A great article on it is "Digging into IDisposable" in MSDN magazine. http://msdn.microsoft.com/en-us/magazine/cc163392.aspx

    This article refers to a Joe Duffy article: "IDisposable guidelines".
    http://www.bluebytesoftware.com/blog...3-20c06ae539ae

  3. #3
    Join Date
    Jun 2008
    Posts
    2,477

    Re: IDispose Best Practices...

    You just need to call Dispose() on all of your fields that implement IDisposable. So, in your case, you would have:

    Code:
    public void Dispose()
    {
        _file.Dispose();
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured