Labels

Monday, October 6, 2008

C# 2.0 - Nullable Types

Hi,

This blog post summarizes the new features of C# 2.0.

Below are the new features been introduced.

§ Partial Classes

§ Static Classes

§ Generic Classes

§ Anonymous methods

§ Iterators

§ Nullable Types

Nullable Types

- Nullable types represent value-type variables that can be assigned the value of null.

- You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

- The syntax T? is shorthand for Nullable<(Of <(T>)>), where T is a value type. The two forms are interchangeable.

int? x = 10; or

double? d = 4.108;

- Use the Nullable<(Of <(T>)>).GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null.

int j = x.GetValueOrDefault();

e.g.

int? i = 5;

int j = i.GetValueOrDefault();

Output - 5

int? i = null;

int j = i.GetValueOrDefault();

Output - 0

- Use the HasValue and Value read-only properties to test for null and retrieve the value.

if(x.HasValue) j = x.Value;

The HasValue property returns true if the variable contains a value, or false if it is null.

The Value property returns a value if one is assigned. Otherwise, a System..::.InvalidOperationException is thrown.

The default value for a nullable type variable sets HasValue to false. The Value is undefined.

- Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type.

int? x = null;

int y = x ?? -1;

- Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;

Hope this helps

Thanks & Regards,

Arun Manglick || Senior Tech Lead

No comments:

Post a Comment