Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does assigning variable to null do?

Tags:

c#

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);
like image 345
Jive Boogie Avatar asked Mar 15 '12 17:03

Jive Boogie


1 Answers

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

like image 133
JaredPar Avatar answered Oct 18 '22 00:10

JaredPar