简体   繁体   中英

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?

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.

you can try with int count = 0;

and add ; not , between two instructions

string needle=textBox1.Text.Trim(); 
cboxSelection = comboBox1.Text;

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;

It's because you are not covering all possibilities within your switch... so there is a "path" in your code in which you get to label6.Text never assigning count .

You should either assign an initial value to count or add a default to your switch

Your switch statement does not cover all cases (it realistically cannot, cboxSelection being a string), so there is a possibility that count does not get anything assigned to before you use it.

Add a default case to the switch to fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM