Reputation: 53263
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();
}
}
Upvotes: 0
Views: 109
Reputation: 11101
I'd change your implementation like so:
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();
}
}
Upvotes: 1
Reputation: 7865
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);
}
Upvotes: 1
Reputation: 726809
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();
}
}
Upvotes: 5