Assign null to ValueType datatype

As we know, memory allocation and data store in memory done in two different ways when we create the object of datatype.

One is data store and assigned to object variable in memory when we create it using value type data type (By Value).

Second way is when we create the object of a class variable then that abject points to the memory location (By Reference).

Object created using by reference option can have null value (like Class Object). The object created using by Value cannot have null value.

Let’s take an example to create an object of integer data type and assign null value to it

int intVariable = null;

When we compile this code compiler generates the below error message.

Error: Cannot convert null to ‘int’ because it is a non-nullable value type

But, there is situation where we need to pass the null values while inserting data for this data type. This can  be achieve using the below code.

int? intVariableWithNull = null;

The above code (‘?’ with datatype) will allow us to create an object of int data type and assign null value to it.

 

Advertisements

#valuetype-with-null-value