Answers

Question and Answer:

  Home  C# (Sharp) Programming Language

⟩ 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').

 188 views

More Questions for you: