I wrote some code today and It was changed by another developer who said it was more safe. I am not sure this is right as I cannot see the advantage of what was done here are some code examples
public byte[] ReadFile(Stream stream)
{
byte[] result = null;
try
{
// do something with stream
result = <result of operation>
}
finally
{
stream.Close();
}
return result;
}
this was changed to
public byte[] ReadFile(Stream stream)
{
byte[] result = null;
// do something with stream
result = <result of operation>
return result;
}
I am quite new to c# should the stream not be closed when you are finished with it ?
In general the first version would be a bad design.
Yes, the Stream should be closed but preferably by the same code (same method) that opened it. That is called separation of concerns and it makes mistakes and confusion much less likely.
So either
ReadFile()accepts for example astring fileNameand Opens and Closes the Stream, orYour method (the 2nd version) should be used in this manner:
Note that the 2nd approach also makes the method more reusable.