开发者

Is it possible to assign a value to a nullable using the conditional operator?

I know I can do this:

Int32 tempInt;
Int32? exitNum;

if (Int32.TryParse(fields[13], out tempInt))
    exitNum = tempInt;
else
开发者_C百科    exitNum = null;

But why can't I do this?

Int32 tempInt;
Int32? exitNum = Int32.TryParse(fields[13], out tempInt) ? tempInt : null;

Is there a way to assign a value to a nullable using the conditional operator?


One side of the conditional operator must be convertible to the type of the other side.
In your case, you have an int on one side, and null (a type-less expression) on the other side. Since neither side is directly compatible with the other side, it doesn't work.

You need to make sure that at least one side is an int?, either by casting, or by writing new int?().

Write Int32.TryParse(fields[13], out tempInt) ? tempInt : new int?()


As others have noted, you have to insure that there is a consistent return type present in the conditional operator. (A subtle feature of C# is that when we must produce a type for an expression amongst several alternatives, the chosen alternative is always somewhere in the expression; we never "magic up" a type that didn't appear.)

If unusual facts about the conditional operator interest you, I recommend my articles on the subject:

http://blogs.msdn.com/b/ericlippert/archive/tags/conditional+operator/

I would add that this is a great opportunity to write an extension method:

static class MyExtensions
{
    public static int? ParseInt(this string s)
    {
        int value;
        return Int32.TryParse(s, out value) ? value : (int?)null;
    }
}

And now you can just say

int? exitNum = fields[13].ParseInt();

which is much more pleasant to read.


You just need to do a cast to Int32? on tempInt

Int32? exitNum = Int32.TryParse(fields[13], out tempInt) ? (int?)tempInt : null;


You can cast null to int? so that both sides have same type:

Int32 tempInt;
Int32? exitNum = Int32.TryParse(fields[13], out tempInt) ? tempInt : (int?)null;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜