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?
string.IsNullOrEmpty(s)Initializable<string> myInitializableString = "Hello";. Add aT Valueand abool IsInitializedproperty to it, and a constructor that takes aTparameter, assigns it toValue, and setsIsInitializedto true. For convenience you can also add an implicit cast back from Initializable<T> to T, so you can write stuff likestring s = myInitializableString;- assuming you find that appropriate.XY Problem. Why do you need to know if it's been assigned or not? Why not just have anelsethat throws the exception?