Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to declare a variable outside of a try catch and for each loop

exception handlingI am a newbie writing code for my c# class. We have to display exception handling but I ran into a red squiggly on my "lines" variable in my for each loop because I put a try catch around the method i declared lines in. How do I fix this? Thanks in advance!

I tried looking for similar issues on other forum with no luck.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can declare the variable lines before try block, like this:


string[] lines = new string[0];
try {
   lines = File.ReadAllText(txtFile);
}
catch (Exception e) {
//....
}

//...

foreach (var line in lines) {
//...
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading