marseilles84
marseilles84

Reputation: 426

setting variable in if statement, then told it's unassigned

I want to initialize an array--I don't know how big it will be. then set it in a condition

so I've got:

string[] my_string;

if(x==2)
{
my_string=File.ReadAllLines("file.txt");
}

string new_string=my_string[1];

It's telling me I've an unassigned local variable, because it's in the condition. How do I get around this?

Upvotes: 1

Views: 312

Answers (3)

MethodMan
MethodMan

Reputation: 18863

Why not Create a List instead and then utilize the File.ReadAllLines("file.txt") also are you including the FilePath along with file.txt here is a free code snippet for you to use I use this alot when I want to load a TextFile into a List as one bulk load...

List<string> lstLinesFromFile = new List<string>(File.ReadAllLines(yourFilePath+ "file.txt"));

from there you can check in the debugger or add a quickwatch to lstLinesFromFile and see all the text that was loaded. each line from there will be accessed link ordinal so use a for loop or foreach loop

Upvotes: 0

keyboardP
keyboardP

Reputation: 69392

At the moment, if x is not equal to 2, then you have no values in your array, but you're still calling that array anyway. One thing you could do is move the new_string assingment inside the if statement. Of course, this may not be the best method if you have other values of x you watch to check against. If so, a Switch..Case might be better.

string[] my_string;
//set new_string to be empty for now
string new_string = String.Empty; 

if(x==2)
{
   my_string=File.ReadAllLines("file.txt");
   //Make sure there are at least two elements
   if(my_string.Length >= 2)       
   //Get the second element of the array (remember, 0 is the first element)
      new_string = my_string[1];
}

Upvotes: 2

SLaks
SLaks

Reputation: 888303

You need to make sure it has a value if x isn't 2.

Upvotes: 4

Related Questions