Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - checking if a variable is initialized

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?

like image 869
Superbest Avatar asked Sep 13 '12 20:09

Superbest


1 Answers

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.

like image 54
McGarnagle Avatar answered Sep 17 '22 06:09

McGarnagle