Notes on C# 2.0 (Nullable Types)

C# 2.0 ( Nullable Types)

Nullable types are constructed using the ? type modifier. This token is placed immediately after the value type being defined as nullable. The type specified before the ? modifier in a nullable type is called the underlying type of the nullable type. Any value type can be an underlying type.

int? i;
Point? nullPoint = null;
i = null;
nullPoint = new Point?(point);
public struct Real
    int internalVal;
    public Real(int realNumber)
        internalVal = realNumber ;
Real? real = new Real?(new Real(3));
The null coalescing operator takes as arguments a nullable type to the left and the given nullable type’s underlying type on the right. If the instance is null, the value on the right is returned otherwise the nullable instance value is returned.
int? i;
i = 10;
int j = 20;
string str = Convert.ToString(i ?? j);
The statement (i ?? j) returns i if i is not null, otherwise it returns j.

The new ?? binary operator allows you to conditionally test for null and use an alternative value instead. For example, consider the following assignment.
int myvalue = (x != null ? x : 0);
With the ?? operator, this can be rewritten as:
int myvalue = x ?? 0;
This indicates to assign the value of x to the myvalue variable or 0 in the case that x is null.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: