The type of the conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'

this is my code:

int? BankName_dd = 
int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue) != -1 ? 
int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue) : null;

      

but I don't understand why this error is causing any suggestions?

+2


source to share


3 answers


this is because the compiler tries to evaluate the right side first.

int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue)

is int and is not null, so there is a mismatch between ie int and null

Even that would be fine if you do. this now wakes up the first parameter as a nullable int



int? BankName_dd = int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue) != -1 ? (int?)int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue):null;

      

SO already answered Link

+2


source


do it like this

int? BankName_dd = int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue) != -1 ? int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue):(int?)null;

      

Your code can be refactored though



int? BankName_dd = int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue);

if(BankName_dd.Value == -1)
   BankName_dd = null;

      

Cause. The relevant section of the C # 3.0 spec is 7.13, the conditional statement is:

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

If X and Y are the same type, then it is the type of the conditional. Otherwise, if the implicit conversion (Β§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression. Otherwise, if the implicit conversion (Β§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. Otherwise, the type of the expression cannot be determined and an error occurs at compile time.

+1


source


result = expression1? expression2: expression3;

Both expression2 and expression3 must be of the same type. And null is not a valid int, so if expression2 is an int, null is not allowed for expression3. Can you use int? as a type for both, casting zero to it and using an implicit int to int conversion? From the left side.

Your expression doesn't make a lot of sense. You do all the work twice.

var result = int.Parse((e.Item.FindControl("BankName_dd") as DropDownList).SelectedValue); 

int? BankName_dd = null;

if(result != -1) BankName_dd = result;

      

+1


source







All Articles