Alex Rivera | Logout

How to tell whether a variable has been initialized in C#?

Asked 2009-07-28T17:41:44.450
26

I know this is a dumb question and I guess it must have been asked before. However I am unable to find an answer to my question.

Here is some sample code (which of course does not compile) to outline my problem:

class test
{
     int[] val1;
     string val2;

     static bool somefunction(test x, test y)
     {
         dosomestuff()

         test result;

         while(result is nothing)
         {
              if(somecondition){result=new test(something);}
         }
     }
}

The problem which I have is in the following line:

while(result is nothing)

This is the syntax from VB, which of course is not what the C# compiler accepts. Could somebody tell me how to resolve the problem?

Edit
Report

1 Answer

39
  • TL;DR:

    if (Object.Equals(myVariable, default(MyVariableType)))

    • Replace myVariable and MyVariableType.

    There are other solutions.

if (myVariable == null) will not work[1] with value types.
(See further below for short intros to  reference types vs. value types   and structs.)

The value types mainly are structs (e.g. DateTime), including[2] the simple types like int, and enumerations. Value types don't support a null value (intrinsically).

The exception and the fix to this are nullable types: Essentially these add null to the possible values of a struct type. They are structurally the same as the Maybe<T> you might know from other languages[3]. You create them with ValueType? (e.g. int?) which is syntactic sugar for Nullable<ValueType>.


Alternatively, instead of using a nullable type, you could compare your variable to its type's default value:
if (Object.Equals(myVariable, default(MyVariableType)))

(This will work both for reference types (objects) and value types.)
Note that you have to replace MyVariableType manually – unfortunately you c

answered 2012-03-15T18:47:12.303

Your Answer