开发者

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

开发者 https://www.devze.com 2023-03-16 15:24 出处:网络
Assume result[11] == string.Empty (i.e. result[11] = \"\") if (result[11] == string.Empty) // this block works fine

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开发者_Go百科 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?


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.


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).


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
}


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;


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号