GurdeepS
GurdeepS

Reputation: 67253

Refactor instance declaration from try block to above try block in a method

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

Upvotes: 0

Views: 71

Answers (2)

tanascius
tanascius

Reputation: 53964

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() )
{
  ..
}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564751

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.

Upvotes: 1

Related Questions