Often I find myself coming across code like this:
try
{
StreamWriter strw = new StreamWriter();
}
However, there is no reference to the object outside the scope of the try block. How could I refactor (extract to field in Visual Studio says there is no field or something) the statement in the try block so that it is declared above the try block so I can use it anywhere in the method?
Thanks
You just need to split the declaration and assignment. If you have Resharper, there’s a method to do the split, but you’ll have to move it manually:
Often, adding the (technically useless)
= null;is required, as well, to prevent potential warnings about using variables before assignment, due to the assignment being in a different scope. This depends a bit on how you’re using the data, though.Also, since
StreamWriteris IDisposable, you’ll want to make sure that you have a finally block that does the disposal, or place the the entire usage in ausingblock.