Type
int cannot contain
null
C#
Example
int value = null; // Compile error CS0037: Cannot convert null to 'int' because it is a non-nullable value type
in some situations it is very convenient for the numeric type to have a value
null.
Example! Working with a database where values are stored
null.
Note!
All data types in the C# can be divided into:
•
Reference types: object, string, class, interface, delegate. Reference types can contain a value
null.
•
value types: int, short, double ..., struct and enum.
Value Types cannot contain a value
null.
null value for value types (int, short, double ..., struct and enum )
C#
// method 1
int? value1 = null;
// method 2
Nullable<int> value2 = null;
C#
Example
int? price = 123;
// method 1
if (price != null)
Console.WriteLine(price);
// method 2
if (price.HasValue)
Console.WriteLine(price.Value);