a DotNetStyling - .Net World by Armen Ayvazyan : Nullable value type variables.
Welcome to DotNetStyling Sign in | Join | Help
Add to Technorati Favorites Add to Google Reader or Homepage Add to My AOL Subscribe in FeedLounge Subscribe in Bloglines Add to Excite MIX Add to flurry Add to Pageflakes Subscribe in NewsGator Online


Nullable value type variables.

.Net Framework 2.0 brought us ability of having nullable value type variables. Maybe it sounds unusually but there are cases where we could use this feature. To make it happen we have to put "?" mark operator after the type, like this:

 

bool? booleanvalue = null;

int? integervalue = null;

 

short? GetShortValue()

{

      return null;

}

 

Now variables booleanvalue and integervalue have null value. And of course we can set null value in any part of code. 
For example I could use this feature to create public property with lazy load initialization:

private int? _field;

           

public int? Property

{

      get

      {

            if (_field != null)

                  _field = 10; //Default value

           

            return _field;

      }

      set { _field = value; }

}

 

We cannot set nullable type of variable to non nullable. We will get compile-time error.

int? integervalue = 3;
int standardInteger = integervalue; //This is wrong implementation

 

To achieve that we have to use new "??" operator.

int? integervalue = null; 

int y = integervalue ?? 3;

 

In case when integervalue will have null value y variable will set to 3 otherwise to integervalue.

Posted: 3. srpna 2007 16:31 by admin
Filed under: ,

Comments

New Comments to this post are disabled