using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class User
{
public int? Age { get; set; }
public int? ID { get; set; }
}
class Program
{
static void Main(string[] args)
{
User user = new User();
user.Age = null; // no warning or error
user.ID = (int?)null; // no warning or error
string result = string.Empty;
User user2 = new User
{
Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result),
// Error 1 Type of conditional expression cannot be determined
// because there is no implicit conversion between '<null>' and 'int'
// ConsoleApplication1\ConsoleApplication1\Program.cs 23 71 ConsoleApplication1
ID = string.IsNullOrEmpty(result) ? (int?)null : Int32.Parse(result) // // no warning or error
};
}
}
}
Question:
Why the following line doesn’t work?
Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result)
// Correction one is
Age = string.IsNullOrEmpty(result) ? (int?) null : Int32.Parse(result)
Why the following line work?
user.Age = null; // no warning or error
Doesn’t work because the
string.IsNullOrEmpty(result) ? null : Int32.Parse(result)is evaluated separately from theAge =part.The compiler can’t figure out what type
string.IsNullOrEmpty(result) ? null : Int32.Parse(result)is supposed to be.It first sees
nullwhich indicates that it’s a reference type, and it sees anintwhich is a value type which seems incompatible. The fact that there exists a type with an implicit cast operator frominttoint?isn’t inferred by the compiler.It could in theory have enough information to figure it out but the compiler would need to be a lot more sophisticated.