C#: Nullable Types

Have you encountered this kind of error ?

SampleError

One solution for this problem is to use Nullable Types. So what are Nullable types ? Nullable Types are instances of System.Nullable<T> struct which have the ability to store both value and null types. Nullable types are good data types to use if you’re usually dealing with database or other data types that will sometimes be assigned with a null value.

For example, if we have declared a Nullable<short> pronounced as “Nullable of Short” we can assign a value of -32,768 to 32,767 and also a null value. The same as true for Nullable<bool> we can assign True, False and lastly null values.

So here we have a simple sample code snippet on how to declare a Nullable types and on how to use some of its properties:

NullableTypesSampleSnippet

So as you can see in the snippet code we have declared num1 and num2 as nullable type. Another way to declare them is to use the int ?  instead of Nullable<int>. The output of the program as follows:

NullableTypeOutput

One property that we used was HasValue which checks if the nullable type has a value other than null will return True and if null will return False as shown in both if statements for num1 and num2.

NullableTypeHasValue

Another property that we used was Value wherein it just gets the current value that the variable is holding.

NullableTypeValue

In our snippet we used the HasValue property in checking the current value of our nullable types but there is another way to check the value as well as assign directly the values by using the ?? Operator or the Null Coalescing Operator.

In this sample code snippet we implement the ?? Operator for checking as well as assigning the required values for num2:

NullableTypesSampleSnippetWithCoalescing

?? Operator returns the left hand operand if it is not null and if it is null then it will return the right hand operand which in our case is the value of num1.

HAPPY CODING 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s