C# – checking if a variable is initialized

Code won’t even compile if the compiler knows a variable hasn’t been initialized.

string s;
if (condition) s = "test";
// compiler error here: use of unassigned local variable 's'
if (s == null) Console.Writeline("uninitialized");

In other cases you could use the default keyword if a variable may not have been initialized. For example, in the following case:

class X
{ 
    private string s;
    public void Y()
    {
        Console.WriteLine(s == default(string));  // this evaluates to true
    }
}

The documentation states that default(T) will give null for reference types, and 0 for value types. So as pointed out in the comments, this is really just the same as checking for null.


This all obscures the fact that you should really initialize variables, to null or whatever, when they are first declared.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)