1.Nullable Types '?' :
In C-sharp Types are divided into 2 categoriesValue Types: Int, float, double, struct, enums etc
Reference Types: Interface, class, delegates, arrays etc
Nullable type is to provide null value to any type.
By Default value types are non-nullable to make them nullable use "?"
Exp:
int i = 0; // i is non nullable because data type of i is int, so i cannot set to null .
int i = null; // it will generate compiler error
so we use "?" to provide null value to 'i'
Syntax:
int? i = null;
Exp:
- {
- static void Main()
- {
- string name = null;
- int i= null;
- int? i = null;
- }
- }
In Line 4 we initialize name to null since it is legal because string is the reference type variable.
In Line 5 we initialize i to null it will generate a compiler error because i is Value type. So, we use "?" in line 6 to make it legal and nullable.
2.Null Coalescing Operator '??' :
This is used to define a default value for nullable types or reference type it return the left hand operand if the operand is not null otherwise it return the right hand operand.
Syntax:
x=y??1;
Exp:
- class Test
- {
- static void Main()
- {
- int availableTickets;
- int? ticketOnSale = null;
- if(ticketOnSale == null)
- {
- availableTickets = 0; // Assign a value when it satisfy null condition
}- else
- {
- availableTickets = (int)ticketOnSale;
} - Console.WriteLine(availableTickets);
}
}
OR
- class Test
- {
- static void Main()
- {
- int availableTickets;
- int? ticketOnSale = null;
- availableTickets = ticketOnSale??0; // null-coalescing operator
- Console.WriteLine(availableTickets);
}
}