Understanding Nullable Types in C#

Do you heard about Nullable types or have you ever used in your project, In this post I am going to write about nullable types.

What is Nullable types?

A Nullable type can accepts correct range of value and along with null value.

Example: Nullable<bool> can accept these three values – true/false/null

Why it is Nullable important?

Nullable types are extremely useful when you retrieve details from database, for example Boolean value in the database can be true/ false or it may be undefined.

There are two types of variables,

  • Value types
  • Reference types

Reference types are Nullable by design, it means you can assign null values to all the reference variables (example: string or  user defined classes).

But in case of  Value types, you can not assign null values. If you assign null values compiler will throw compile time errors. In order to achieve we have to apply some technique to make the value type variable accept null values.

before that consider the below simple program in which I am assigning a null value to a value type variable.

You will get the following kind of error message – “Cannot convert null to ‘int’ because it is a non-nullable value type”

How to solve this problem?

Option 1: Using Nullable struct with value type.

Option 2: Using ? operator with value type

What are value types?

In C# any definition with “struct” keyword, then it is Value type – example Int, Float,Double, etc all these are value types.

What are Reference Types?

In C# any definition with “Class” keyword, then it is Reference type – example String

I will write more about Nullable in upcoming post as well. please do share your thoughts in comments section if you found this article useful to you.

0 comments… add one

Leave a Comment