Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Error: Unassigned local variable error when using "switch"?

What I want to achieve is, to show count of lines ending with/starting with (user selects type by comboBox1) given character (by textbox1).

Trying to compile this code:

string needle=textBox1.Text.Trim(), cboxSelection = comboBox1.Text;
int count;
switch (cboxSelection)
{
    case "Starting with":
        count = File.ReadLines(openFileDialog1.FileName).Count(line => Regex.IsMatch(line, "^" + needle + ".*$"));
        break;
    case "Ending with":
        count = File.ReadLines(openFileDialog1.FileName).Count(line => Regex.IsMatch(line, "^.*" + needle + ".*$"));                    
        break;
}
string strCount = count.ToString(); // error line
label6.Text = "There are " + strCount + " lines " + cboxSelection + " " + needle + " character.";

Getting error message: Use of unassigned local variable 'count'. What am I missing?

like image 400
heron Avatar asked Dec 26 '22 22:12

heron


2 Answers

Your local count variable has not been definitely assigned at the point of use. Either declare it as

int count = 0;

or add a default clause to your case statement:

default: count = 0;

Your switch statement is not guaranteed to enter either case, so count can remain unassigned. If one of the two cases is required, you should throw an exception in your default case:

default: throw new ArgumentException("Invalid selection");

You should always use a default case in your switch statements either to assign a default or to guard against unexpected states.

like image 191
Lee Avatar answered Jan 24 '23 03:01

Lee


Count isn't assigned on all code paths. If your switch doesn't have "Starting with" or "Ending with", it will be null.

You can initialize it:

int count = 0;

like image 33
David B Avatar answered Jan 24 '23 04:01

David B