Question

Is there way you can suggest to help to get rid of calling the Initialize() and Close() methods and replace it a using block?

Or this approach is totally OK?

(Idea is to ensure the Writer will be disposed when a consumer of FooWriter writes some strings and finishes with this.)

class Program
    {
        static void Main(string[] args)
        {
            var writer  = new FooWriter();

            writer.Initialize();

            foreach (var s in args)
                writer.Write(s);

            writer.Cose();
    }


public class FooWriter
{

    public StreamWriter Writer;

    public void Initialize()
    {
        Writer = new StreamWriter("MyFile.txt", false);
    }

    public void Write(string line)
    {
        if(Writer==null)
            throw new NullReferenceException(Writer, "Writer"); // Guard Writer

        Writer.WriteLine(line);
    }

    public void Close()
    {
        Writer.Dispose();
    }

}
Was it helpful?

Solution

You can do that by making your FooWriter an IDisposable. and moving the initialization into its constructor:

public class FooWriter : IDisposable {

    public StreamWriter Writer;

    public FooWriter()
    {
        Writer = new StreamWriter("MyFile.txt", false);
    }

    public void Write(string line)
    {
        // You do not need to guard the writer, because constructor sets it
        if(Writer==null)
            throw new NullReferenceException(Writer, "Writer"); // Guard Writer

        Writer.WriteLine(line);
    }

    public void Dispose()
    {
        Writer.Dispose();
    }

}

OTHER TIPS

you can make FooWriter implement IDisposable and call Initialize() in the constructor, you can then use at as follows:

class FooWriter : IDisposable
{
   private StreamWriter Writer;
   public FooWriter()
   {
      Writer = new StreamWriter("MyFile.txt", false);
   }
   public void Write(string line)
   {
     Writer.WriteLine(line);
   }
   public void Dispose()
   {
        Writer.Dispose();
   }
}


// use it

using (var writer = new FooWriter())
{
  foreach (var s in args)
                writer.Write(s);
}

I'd change your implementation like so:

  • Make the class implement IDisposable
  • Initialize the writer in the constructor
  • Remove the exception

    public class FooWriter : IDisposable { public StreamWriter Writer { get; private set; }

    public FooWriter(string fileName)
    {
        Writer = new StreamWriter(fileName, false);
    }
    
    public void Write(string line)
    {                        
        Writer.WriteLine(line);
    }      
    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    
    protected virtual void Dispose(bool disposeManaged)
    {
        if (disposeManaged)
            Writer.Dispose();
    }
    

    }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top