sharing about .NET and technology RSS 2.0
 Wednesday, August 24, 2005

In .NET 1.1 you cannot assign the NULL value to a value type (e.g. int, float, etc.). There are some situations where this is needed, typically in database scenarios. In .NET 2.0 there is a new type called nullable. The nullable type implements the INullableValue interface and looks like:

public interface INullableValue
{
   bool HasValue { get; }
   object Value { get; }
}

The idea is that a nullable type combines a value (Value) of the underlying type with a boolean (HasValue) null indicator. The underlying type of a nullable type must be a value type.

Nullable<int> x = 9;

Debug.Assert(x.HasValue);
Debug.Assert(x == 9);
Debug.Assert(x.Value == 9);
Debug.Assert(x.GetValueOrDefault(5) == 9);

x = null;
Debug.Assert(x.HasValue == false);
Debug.Assert(x.GetValueOrDefault(5) == 5);

You can also use the ? type modifier to denote a nullable type.

int? y = 9;
Debug.Assert(y.HasValue);
Debug.Assert(typeof(int?) == typeof(Nullable<int>));

In .NET 2.0 there is a new operator, called the null coalescing operator, ??. For example the statement x ?? y is x if x is not null, otherwise the result is y. Note that this operator also works with reference types.

int? a = null;
int? b = 6;
Debug.Assert((a ?? b) == b);
a = 9;
Debug.Assert((a ?? b) == a);
b = null;
Debug.Assert((a ?? b) == a);

Wednesday, August 24, 2005 12:48:05 AM (Romance Standard Time, UTC+01:00)  #    Comments [0] -

Navigation
Archive
<January 2009>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2009
Christoph De Baene
Sign In
Statistics
Total Posts: 154
This Year: 0
This Month: 0
This Week: 0
Comments: 166
All Content © 2009, Christoph De Baene
DasBlog theme 'Business' created by Christoph De Baene (delarou)