if (myInt != int.MinValue)An alternative now exists with nullable types, nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying type, plus an additional null value. How to declare nullable type of type Int32, both of the following declarations compile to the same IL code.
{
// Int has been set.
}
if (myDateTime != DateTime.MinValue)
{
// DateTime has been set.
}
int? a = null;You can determine whether a nullable type has a value by using the HasValue property, you can also return the value using the Value property if no value is assigned calling this method will result in a System.InvalidOperationException.
Nullable<int> a = null;
If you wish to default the value of a nullable type when reading its value you can use the null coalescing operator, this can also be used with value types.
int? a = null;The code above defaults the value of a when null to -1, which is very like the statement below but a great deal neater.
Console.WriteLine(a ?? -1);
int? a = null;
Console.WriteLine(a == null ? -1 : a);
No comments:
Post a Comment