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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With