In C#, as you probably know that a value type cannot have null. So if you define a bool it can have either a true or a false. But there are situations that you would also like to cater for null values. For example, if you’re working with a database and you have a table called Customers which has a column called Birthdate. Birthdate can be nullable Customers.Bithday (datetime NULL)
because not everyone wants to put in their birthdate. In that case, if you want to map that table to a C# class that’s one of the cases where you use a Nullable type. Let’s see how nullable types work in action.
So I define a DateTime here call it date and set it to null. See, we immediately got an error. Why? Because DateTime is a value type and as a result, cannot be set to null.We can solve that issue by using Nullable.
Nullable is a generic structure that is defined in the System namespace. So, now we can have a variable that can have either null or a valid DateTime. We can rewrite this code and make it a little bit shorter. The shorthand of defining nullables is to type the value type and then append a question ?
mark.
Now let’s take a closer look at the members of a nullable type.
Here are the properties and methods of the nullable type: GetValueOrDefault, HasValue and Value are the three members that you’ll be using all the time. Let me show you the difference. It’s best to show them by an example. So I’m going to put them on the console,
using System; namespace NullableType { class Program { static void Main(string[] args) { DateTime? date = null; Console.WriteLine("GetValueOrDefault(): " + date.GetValueOrDefault()); Console.WriteLine("HasValue: " + date.HasValue); Console.WriteLine("Value: " + date.Value); } } }
Let’s run the application and see what happens. We got an exception; the application crashed.
Let’s take a closer look-
Here, GetValueOrDefault returns a value, if the object has been initialized with an actual value or returns the default value for that data type if it’s not. In this case, we set our date to null, it’s trying to return the default value or a DateTime which is day one of months one of year one. If you define a nullable bool, GetValueOrDefault method would return false if you forget to initialize it.
HasValue returns true if the object has a value, but if it’s null, it returns false. In this case, because it’s null, it’s returning false.
But look at the last one here. When we access the Value property we got an exception and that exception is of type InvalidOperationException. It’s saying nullable object must have a value.
So basically the lesson here is when you access the Value property you should make sure that your object has a value. Otherwise, you’re gonna get an exception.
That’s why we have GetValueOrDefault method here. So, GetValueOrDefault() is the preferred way of getting the value. This way, if the object has a value you will get it; otherwise, you’ll get the default value for that value type instead of getting an exception.
Now let me show you something else about Nullables.
I actually set the date value here. So new DateTime, let’s say “2020, first of January”. I define another DateTime. Let’s call it date2 and set ‘date‘ here. See, we immediately got an error. Why? Because we’re trying to put a nullable DateTime into a DateTime and the compiler doesn’t know how to respond to that. What if it’s null? What should we do? Compiler doesn’t know. So in situations like that, if you get that error what you need to do is access that GetValueOrDefault method.
In that case, because we have a value here that will go straight into this date2. Let’s verify that.
There you go. All good. Now let’s take a look at the other scenario. This time, I define a nullable DateTime and try to put date2 here.
So in this case, you don’t need to call this method or do any casting. A value type can easily be converted to a nullable type, as you see here. So let’s display date3.GetValueOrDefault.
There you go and all the output is as expected.
Null Coalescing operator
Now let me introduce you to an operator that is pretty useful when writing code. It’s called null coalescing operator. I going to modify my previous example
Here I set date to null. Let’s say we would like to write a code like this- If date is not null set date2 to date. Otherwise date.GetValueOrDefault because of the reason I explained earlier. Otherwise, if date is null, we would like to give date2 some default date, let’s say, DateTime.Today. So in that case, because date here is null, else block will be executed in which case we set today’s date to date2.
Let’s verify date2. So, today is 19th of June, 2020. Great!
Now we can rewrite this block here much shorter using Null coalescing operator ??
. Let me show you how it works.
So, here I used Null coalescing operator after date ; which is double question mark and then DateTime.Today. Basically, how we read that is “if date has a value, put it here; otherwise, use this DateTime.Today”. It’s a little bit similar to the tertiary operator. Well, that’s pretty much about Nullable types. I hope you enjoyed this article and thank you for reading.
Great article. This article help me a lot.
Thanks for complement! Glad to know that my article helped you. 🙂
Wow … সেই Article … দারুণ একটা বিষয় জানলাম । Nullable Type টা এভাবে গভীর ভাবে চিন্তা করে দেখি নাই ।
Thanks vai! Thanks for read!