I want to check if a variable is initialized at run time, programmatically. To make the reasons for this less mysterious, please see the following incomplete code:
string s;
if (someCondition) s = someValue;
if (someOtherCondition) s = someOtherValue;
bool sIsUninitialized = /* assign value correctly */;
if (!sIsUninitialized) Console.WriteLine(s) else throw new Exception("Please initialize s.");
And complete the relevant bit.
One hacky solution is to initialize s with a default value:
string s = "zanzibar";
And then check if it changed:
bool sIsUninitialized = s == "zanzibar";
However, what if someValue or someOtherValue happen to be “zanzibar” as well? Then I have a bug. Any better way?
Code won’t even compile if the compiler knows a variable hasn’t been initialized.
In other cases you could use the
defaultkeyword if a variable may not have been initialized. For example, in the following case:The documentation states that default(T) will give
nullfor reference types, and0for 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
nullor whatever, when they are first declared.