C# Nullable Type question [duplicate]
Possible Duplicate:
Nullable types and the ternary operator. Why won’t this work?
for example:
int? taxid;
if (ddlProductTax.Selecte开发者_高级运维dValue == "") {
taxid = null; }
else {
taxid = Convert.ToInt32(ddlProductTax.SelectedValue);
} //Correct
But
int? taxid;
taxid = (ddlProductTax.SelectedValue == "" ? null : Convert.ToInt32(ddlProductTax.SelectedValue)); //Error
It error say and int32 cannot implicit convert.
The ( ? truepart : falsepart); is not short of (if ..else..) ?
The last two operands of the ternary operator should both yield the same type.
Cast either side to int?
:
taxid = ddlProductTax.SelectedValue == "" ?
(int?)null
: Convert.ToInt32(ddlProductTax.SelectedValue);
You can see the exact behavior in the specification:
- 7.12 Conditional operator
- 6.1 Implicit conversions
Duplicate
For why it works.
Nullable types and the ternary operator: why is `? 10 : null` forbidden?
Here's the fix:
string x = "";
int? taxid;
taxid = (x == "" ? null : (int?) Convert.ToInt32(x)); // add the int? cast
Console.WriteLine(taxid);
Apply this correction and it should work.
int? taxid;
taxid = (ddlProductTax.SelectedValue == "" ? null : new int?(Convert.ToInt32(ddlProductTax.SelectedValue))); //Now it works.
Here is a little helper method
taxid = GetNullableInt32(ddlProductTax.SelectedValue);
public static int? GetNullableInt32(string str)
{
int result;
if (Int32.TryParse(str, out result))
{
return result;
}
return null;
}
I think that it's down to the way in which the expressions are evaluated.
With the ? :
construct both of the results must evaulate to the same type and here there is no implicit conversion between the null
value and an Int32
.
Try:
taxid = (ddlProductTax.SelectedValue == "" )? Convert.ToInt32(null) : Convert.ToInt32(ddlProductTax.SelectedValue);
精彩评论