Thursday, October 14, 2010

Nullable Type in C-Sharp

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

The syntax T?

Assign a value to a nullable type in the same way as for an ordinary value type, for example
int? x = 10; or
double? d = 4.108;

Use GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null,
for example int j = x.GetValueOrDefault();

Use HasValue and Value read-only properties to test for null and retrieve the value, for example if(x.HasValue) j = x.Value;

  • The HasValue property returns true if the variable contains a value, or false if it is null.
  • The default value for a nullable type variable sets HasValue to false. The Value is undefined.
  • The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.

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, for example

int? x = null;

int y = x ?? -1;

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.