C# (Sharp) Programming Language Question:

Download Job Interview Questions and Answers PDF

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

C# (Sharp) Programming Language Interview Question
C# (Sharp) Programming Language Interview Question

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

Download C# (Sharp) Programming Language Interview Questions And Answers PDF

Previous QuestionNext Question
How do I get deterministic finalization in C#?Why do I get an error (CS1006) when trying to declare a method without specifying a return type?