开发者

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

开发者 https://www.devze.com 2022-12-24 01:52 出处:网络
Often 开发者_如何学运维I find myself coming across code like this: try { StreamWriter strw = new StreamWriter();

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:

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.


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

精彩评论

暂无评论...
验证码 换一张
取 消