JG Vimalan's Blog

It is all about coding!

Type of conditional expression cannot be determined because there is no implicit conversion between ‘null’ and ‘int’

I got the error ‘Type of conditional expression cannot be determined because there is no implicit conversion between ‘<null>’ and ‘int” in the following line of code,

        /// <summary>
        /// This method gets the null or integer value from the given object value
        /// </summary>
        /// <param name=”obj”></param>
        /// <returns></returns>
        public static Nullable<int> GetNullOrInt(object obj)
        {           
            return obj == null ? null : obj.ToInteger();
        }

In the above method, I am using a ternary operator to check if an object is null or not and return its integer value.

To fix this error, I have added another line of code as shown below,

        /// <summary>
        ///
        /// </summary>
        /// <param name=”obj”></param>
        /// <returns></returns>
        public static Nullable<int> GetNullOrInt(object obj)
        {
            Nullable<int> value = null;
            return obj == null ? value : obj.ToInteger();
        }

instead of returning the null value, I have created a nullable variable and used it in the return statement. This worked.

Advertisements

April 15, 2011 - Posted by | C#.NET

6 Comments »

  1. I got a similar kind of issue with date time. Your post gave me a hint to fix that. Thank you.

    Comment by Udhay | May 4, 2011 | Reply

  2. How to fix for following

    public int? L2TopicId { get; set; }

    I am getting same error.

    Comment by ANSHUL | November 21, 2011 | Reply

  3. thanks

    Comment by nawfal | April 7, 2012 | Reply

  4. Thanks this worked for me!

    Comment by Steve | October 12, 2012 | Reply

  5. The error comes when you use ternary operation and either both the expressions doesn’t have same return type or there is no implicit conversion from one type to other type. Very well explanation is given in below tutorial – http://a1ashiish-csharp.blogspot.com/2012/12/Type-of-conditional-expression-cannot-be-determined-as-byte-and-int.html

    Comment by a1ashiish | December 28, 2012 | Reply

  6. use null as int like for example

    result.L2TopicId = (reader[“L2TopicId “] is DBNull) ? null as bool? : Convert.ToBolean(reader[“L2TopicId “].ToString());

    Comment by christian | January 15, 2014 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: