Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use (int?) null when adopt object initializer?

Tags:

c#

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
like image 873
q0987 Avatar asked Aug 04 '26 08:08

q0987


1 Answers

Its because the ternary operator needs the return types to be the same type.

In the 1st case "null" could be a null of any reference type (not just int?) so to make it explicit to the compiler it needs casting.

Otherwise you could have

string x = null;
Age = string.IsNullOrEmpty(result) ? x: Int32.Parse(result)

which is obviously a bit cuckooo.

like image 195
neil danson Avatar answered Aug 06 '26 21:08

neil danson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!