Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

Please look at below code :-
C#
using System.IO;
using System;
class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
        int? i;
        i = 0==1?1:(int?)null;   //why here I have to cast null to int nullable
        i = null;                //not here
    }
}


Question is on comments. Please explain. This is weird.
Posted

Because 1 is not a nullable int, so if you write this:
C#
int? i = 0==1 ? 1 : null;

The compiler tries to return a Value type (1, integer, which can't be null) and a Reference type (null) and says "These aren't the same type, and there is no implicit conversion"

When you specify the type of the second value:
C#
int? i = 0==1 ? 1 : (int?) null;
It realises what you are trying to do because there is an implicit conversion from int to nullable int
 
Share this answer
 
Quote from MSDN[^]:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

There is no implicit conversion from null to int or vice versa. There is however conversion from int to nullable int and from null to nullable int too.
C#
i = 0==1?1:null;       // int vs. null - doesn't work
i = 0==1?1:(int?)null; // int vs. int? - works
i = 0==1?(int?)1:null; // int? vs. null - works as well
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900