q0987
q0987

Reputation: 35982

Why this line doesn't work user.Age = (result[11] == string.Empty) ? (int?) null : Int32.Parse(result[11])

Assume result[11] == string.Empty (i.e. result[11] = "")

if (result[11] == string.Empty) // this block works fine
{
    user.Age = Int32.Parse(result[11]);
}
else
{
    user.Age = null;
}

// the following line will throw exception
user.Age = (result[11] == string.Empty) ? (int?) null : 
                                          Int32.Parse(result[11]);

System.FormatException was unhandled Message=Input string was not in a correct format. Source=mscorlib StackTrace: at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, >> >> NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s)

To me, the above two blocks are same. Then why the first one works while the second one doesn't?

Upvotes: 0

Views: 360

Answers (5)

Adriano Carneiro
Adriano Carneiro

Reputation: 58615

Everyone answered how you are trying to parse invalid strings as integer. They are right. However, apparently people have missed that your code is not equivalent, because you have inverted the ternary clauses. This would be your equivalent code:

//if this is your code:
if (result[11] == string.Empty) // this block works fine
{
    user.Age = Int32.Parse(result[11]);
}
else
{
    user.Age = null;
}

//This is your equivalent ternary. You have inverted here
user.Age = (result[11] == string.Empty) ? Int32.Parse(result[11]) : 
                                          null;

Upvotes: 1

Jethro
Jethro

Reputation: 5916

The result that you are trying to parse as Integer is not a valid Integer, hence the exceptions. Rather do the following.

if (!String.IsNullOrEmpty(result[11]))
{
    if (!Int32.TryParse(result[11], out user.Age))
        user.Age = null; // not really needed
}

Upvotes: 1

Yann Olaf
Yann Olaf

Reputation: 597

I have tried this:

        var value = "";
        int? age;

        if (value != string.Empty)
        {
            age = Int32.Parse(value);
        }
        else
        {
            age = null;
        }


        age = (value == string.Empty) ? (int?)null : Int32.Parse(value);

and it works fine (I have changed the == to != in the first if).

Upvotes: 1

James Johnston
James Johnston

Reputation: 9492

The blocks are not the same.

if (result[11] == string.Empty) // this block works fine
{
    user.Age = Int32.Parse(result[11]);
}

That block should actually not work, because the block will only parse an empty string. Switch the code in the "if" block and the "else" block, and it will be identical to your ternary "? :" operator.

Upvotes: 7

Tim
Tim

Reputation: 8921

result[i] might return 'object', ergo cast:

     (string) result[i] == ....
     Int.Parse(  (string) result[i] )

Upvotes: 0

Related Questions