Why should we use Nullable Type?
There are a number of scenarios where it will be good to use a nullable type. Look at the below scenarios,
- Nullable Type is a special type of value-type that can contain a value of their normal range as well as null value. A value type variable cannot contain null value so we can use nullable type which has the ability to contain a value of its normal range as well as null.
- We cannot assign null to int, bool, double, char values while retrieving values from the database. So it is recommended to use nullable types instead of value types in a case where we want to store the null value.
- Useful with binding in WPF to store a default value when UI property bind does not contain any data.
- In many scenarios, we use reference type only to store a null value. In these cases, reference type can be replaced with nullable type.
Likewise, there are numerous scenarios where nullable is useful.
What is Nullable Type?
A Special type of value type variable which can contain the value of its normal range as well as null value.
Syntax of Nullable Types is,
- <data_type>? <variable_name> = value;
- int? a = 25;
- //or
- Nullable<<data_type>> <variable_name> = value;
- Nullable<int> a = 25;
We can use any one of them, both are the same
Nullable of bool type can contain true and false as well as null. Nullable of int type can contain any value from the range of int(-2147483648 to 2147483647) as well as null.
- bool? a= true;
- int? b= null;
Nullable Types can only be used with value-type, not with a reference type as they already contain the null value.
- Nullable<string> str = "75";
This will generate a compile time error as "The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' Name can be simplified". The reason is 'string' is a reference type and it already contains the null value. Nullable can only be used with value-types.
Instances of the System.Nullable<T> struct.
Nullable types cannot be nested.

Join the conversation! Your thoughts help the community grow.