Reputation: 85
I have the following code that I use to close a stream.
void CloseStream(Stream s)
{
if (s != null)
s.Close();
}
void CloseStream(HttpWebResponse s)
{
if (s != null)
s.Close();
}
void CloseStream(StreamReader s)
{
if (s != null)
s.Close();
}
The code works perfectly but I would like to refactor the 3 methods if it's possible. Ideally the method would look like that:
void CloseStream(Object obj)
{
obj.Close();
}
But I cannot do obj.Close() because the Object class does not implements such a method. So I was wondering if any of you had any idea how to resolve it.
Thanks for your time, Kevin
Upvotes: 3
Views: 133
Reputation: 236318
All these 'streams' are disposable, so use Dispose()
instead of Close()
:
void CloseStream(IDisposable s)
{
if (s != null)
s.Dispose();
}
Also consider to use functionality built-in .Net Framework - using
statement will automatically dispose disposable object without any additional calls to CloseStream
:
using(StreamReader reader = File.OpenText(path))// create disposable here
{
// use disposable
}
This code will automatically check if disposable is not null
and dispose it at the end of using
block. Code above block will compile into:
StreamReader reader = File.OpenText(path);
try
{
// use disposable
}
finally // will be executed even in case of exception
{
if (reader != null)
reader.Dispose(); // internally calls Close()
}
Upvotes: 9
Reputation: 117154
They should all implement IDisposable
which implements Dispose
(which does the same work as Close
).
So try:
void CloseStream(IDispsable obj)
{
obj.Dispose();
}
Upvotes: 0
Reputation: 54897
All three classes implement IDisposable
, and the Dispose
method closes the underlying stream, so you can call that instead:
void CloseStream(IDisposable s)
{
if (s != null)
s.Dispose();
}
Upvotes: 4