Search content within the blog

Monday, May 4, 2009

Nullable Type in c# - Part II

Comparisons

Comparisons occur in a similar manner to the mathematical operations. The operands in a comparison are lifted to both being nullable. Then, the comparison is done. If one of the operands contains a null, the result of the comparison will be false.

If comparing for equality (or non-equality), two variables containing null will be considered equal. A variable containing null compared to a variable with any value will be considered not equal. The following are some examples of comparisons:

int abc = 123;
int xyz = 890;
int? def = null;
int? uvw = 123;

Comparison Result
abc == xyz // false
abc == def // false
def == null // true
abc == uvw // true
uvw == null // false
uvw != null // true

In all comparisons, the result is a Boolean value of true or false. When doing relative comparisons, you also will get a returned Boolean value of true or false; however, a null value impacts things. In the case of relative comparisons, if either (or both) of the value is null, a value of false will be returned. The following are some examples of relative comparisons and their results. These use the same defined variables from above.

Comparison Result
abc > uvw // false, they are equal
abc < def // false, def is null
uvw < def // false, because def is null
def > null // false, because right side is null
uvw > null // false, because right side is null

Removing Nullability

C# also gets an additional operator in its newest version. This is the ?? operator used for null coalescing. The null coalescing operator takes the following format:

returnValue = first ?? second;

In this case, if first is not null, its value will be returned to returnValue. If first is null, then the value of second will be returned. You should note that returnValue can be either a nullable or non-nullable variable.

If you wanted to move a nullable varaible's value to a non-nullable version, you could do the following:

int? ValA= 123;
int? ValB = null;

int NewVarA = ValA ?? -1;
int NewVarB = ValB ?? -1;

When the above is completed, NewVarA will contain the value of 123 because ValA was not null. NewVarB will contain the value of -1 because ValB was null. As you can see, this allows you to change variables with a null value to a defaulted value. In this case, the defaulted value is -1.


In Conclusion...

In conclusion, the newest version of C# allows for a nullable type. These types can be used with non-nullable types with little thought and little effort because the conversions will be built into the language. The nullable types should make working with database records and other optional information much easier going forward.

Nullable types is a part of the ECMA-334 version of C#. You'll need a compiler that supports this C# standard in order to use nullable types. Visual Studio 2005 supports this standard.

No comments:

Post a Comment