How can I get around scope problems in a try/catch?

If you try to instantiate the class inside the try, it'll be out of scope when you try to access it from the catch block. A way to get around this is to do the following:

Connection conn = null;

try

{

conn = new Connection();

conn.Open();

}

finally

{

if (conn != null) conn.Close();

}

By setting it to null before the try block, you avoid getting the CS0165 error (Use of possibly unassigned local variable 'conn').

Showing Answers 1 - 1 of 1 Answers

ans:

Answer:

If you try to instantiate the class inside the try, it'll be out of scope when you try to access it from the catch block. A way to get around this is to do the following:

Connection conn = null;

try

{

conn = new Connection();

conn.Open();

}

finally

{

if (conn != null) conn.Close();

}

By setting it to null before the try block, you avoid getting the CS0165 error (Use of possibly unassigned local variable 'conn').

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions