C# - 12 - Fun with nulls.
[C# 2.0]
Reference type variables can, by their very nature, be null. But what about value types? They can be 'made' nullable by adding the '?' qualifier … as in
Making something nullable assigns it two read-only properties: HasValue and Value … thus:
So what would have happened above if you hadn't tested? You'd have gotten an error because x might be null and z doesn't support nulls.
An alternative to testing HasValue is to use '??' (the null coalessor).
… in this example if x has a value then z will be given it, otherwise z will be set to 3.
One final trick: the null coalessor can be used with reference types too. Consider:
Simples.
.
page revision: 3, last edited: 23 Nov 2010 01:18