Exception Handling in C# - The Solution, but More Issues
(Page 3 of 8 )
The solution to this lost release problem depends on the language you're using. In C++ you can release the resource in the destructor of an object held on the stack (the misnamed Resource Acquisition Is Initialization idiom). In Java you can use a finally block. C# allows you to create user-defined struct types that live on the stack but does not allow struct destructors. (This is because a C# destructor is really a Finalize method in disguise and Finalize is called by the garbage collector. Structs, being value types, are never subject to garbage collection.) Therefore, initially at least, C# must follow the Java route and use a finally block. A first cut implementation using a finally block might look like this:
private
static char[] ReadSource(string filename)
{
try
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
char[] source = new char[length];
TextReader reader = file.OpenText();
reader.Read(source, 0, length);
}
finally
{
reader.Close();
}
return source;
}
This version has had to introduce a try block (since a finally block must follow a try block) which isn't in the ideal solution but apart from that it's the same as the "ideal" version of ReadSource. It would be a reasonable solution if it worked. But it doesn't. The problem is that the try block forms a scope so reader is not in scope inside the finally block and source is not in scope at the return statement.
Next: A Second Attempt >>
More C# Articles
More By Jon Jagger