简体   繁体   中英

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
    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?() 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM