views:

23

answers:

2

Hi,

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

+1  A: 

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:

StreamWriter strw = null;
try
{
    strw = new StreamWriter();
}
catch()
{ // ...

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 StreamWriter is IDisposable, you'll want to make sure that you have a finally block that does the disposal, or place the the entire usage in a using block.

Reed Copsey
That won't compile. "strw" is declared twice. Remove "StreamWriter" from inside the try {} and it should be fine.
Peter
@Peter: Sorry - stupid copy/paste error. Fixed.
Reed Copsey
Hi. StreamWriter is just an example type, am aware of the IDisposable issue. Thanks :) I don't have Resharper at the moment, waiting for the final release of 5.0 so I can get it for 2010.
dotnetdev
@dotnetdev: You can get the RC for free right now... http://www.jetbrains.com/resharper/beta/beta.html
Reed Copsey
A: 
StreamWriter strw = null;
try
{
  strw = new StreamWriter();
}

But for a StreamWriter (which is IDisposable) it is even better to use the using-keyword:

using( StreamWriter strw = new StreamWriter() )
{
  ..
}
tanascius

related questions