Exception Handling in C# - Do it Yourself?
(Page 7 of 8 )
It's instructive to consider what would happen if TextReader didn't implement the IDisposable interface. The lessons from this will show us how to implement Disposability in our own classes. One solution is the Object Adapter pattern. For example:
public sealed
class AutoTextReader : IDisposable
{
public AutoTextReader(TextReader target)
{
// PreCondition(target != null);
adaptee = target;
}
public TextReader TextReader
{
get { return adaptee; }
}
public void Dispose()
{
adaptee.Close();
}
private readonly TextReader adaptee;
}
which you would use like this:
using
(AutoTextReader scoped = new AutoTextReader(file.OpenText()))
{
scoped.TextReader.Read(source, 0, length);
}
To make things a little easier you can create an implicit conversion operator:
public sealed
class AutoTextReader : IDisposable
{
...
public static implicit operator AutoTextReader(TextReader target)
{
return new AutoTextReader(target);
}
...
}
which would allow you to write this:
using
(AutoTextReader scoped = file.OpenText())
{
scoped.TextReader.Read(source, 0, length);
Next: struct Alternative >>
More C# Articles
More By Jon Jagger