In the following I get a compile time error that says "Use of unassigned local variable 'match'" if I just enter string match; but it works when I use string match = null; So what is the difference and in general, if a string is not being assigned a value right away should I be assigning to null like this?
string question = "Why do I need to assign to null";
char[] delim = { ' ' };
string[] strArr = question.Split(delim);
//Throws Error
string match;
//No Error
//string match = null;
foreach (string s in strArr)
{
if (s == "Why")
{
match = "Why";
}
}
Console.WriteLine(match);
The C# language prevents the use of a local until it has been definitively assigned a value. In this example the compiler doesn't understand the semantics of Split
and has to assume that strArr
can be an empty collection and hence the body of the loop could potentially not execute. This means from a definitive assignment perspective the foreach
doesn't assign match
a value. Hence it's still unassigned when you get to WriteLine
By changing the declaration to string match = null
the value is marked as definitely assigned from the very start. The loop calculation hence doesn't matter
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