Fun With Nullables: Nullable object must have a value
Nullable types is a great addition to the .NET framework. Having nullable types allows us write cleaner code. However, nullable types can be a source of problems, especially if you are still not well familiar with them. While there is no rocket science involved with nullable types, for beginner developers nullable types seem complex.Under the hood, nullable types are instances of the System.Nullable<T> struct. In other words, nullable types are in essence generic types and the short and nice question mark that you append to types is just so called syntactical sugar.
So, let's bring one instance of using nullable types where things can go wrong. Look at the code snippet below.
DateTime? yourBirthday = null;
DateTime? myBirthday = yourBirthday.Value;If you think this code snippet is purely hypothetical, think twice. We've come accross half a dozen of posts on forums with similar code posted by programmers having trouble with nullable types.
As you may guess, the code above is correct C# syntax-wise and as expected the compiler does not complaint. Alas, a runtime error is guaranteed when the above code is reached. More specifically, you will get
[InvalidOperationException: Nullable object must have a value.]In MSDN we read what the Value property is:
The value of the current Nullable<T> object if the HasValue property is true. An exception is thrown if the HasValue property is false.
Let's quickly fix the above code. Initially, you may think about the following code:
DateTime? yourBirthday = null;
DateTime? myBirthday = yourBirthday.HasValue? yourBirthday.Value : null;As soon as you press F5 in Visual Studio, the compilator starts complaining that
Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'null'. Finally, the fixed code below compiles just fine and gives you no runtime exception.DateTime? yourBirthday = null;
DateTime? myBirthday = yourBirthday.HasValue? yourBirthday.Value : (DateTime?) null;Happy coding!

0 comments:
Post a Comment