Monday, March 30, 2015

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

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

Answer: </P><P align=justify>If you try to instantiate the class inside the try, it&#39;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: </P><P align=justify>Connection conn = null; </P><P align=justify>try </P><P align=justify>{</P><P align=justify>conn = new Connection();</P><P align=justify>conn.Open();</P><P align=justify>}</P><P align=justify>finally</P><P align=justify>{ </P><P align=justify>if (conn != null) conn.Close(); </P><P align=justify>}</P><P align=justify></P><P align=justify>By setting it to null before the try block, you avoid getting the CS0165 error (Use of possibly unassigned local variable &#39;conn&#39;).

Tags:Interview Questions, Microsoft, C#,

Please submit your Interview Answer for the above Question via replying to this post. Thank you for visiting to our blog, Have a Good Day!.



Sponsor Advertisement



Human Resource Management Software

Human Resource Management Software

Powerful, configurable software for human resources management that is easy to manage and remarkably cost-effective, whatever the size of your company. Now there’s a smarter, more efficient way to handle all of your people-related activities. Easy-to-use system manages the full hire-to-retire lifecycle...

No comments:

Post a Comment