开发者

Why can't I cast an int to a string within this ternary operation

开发者 https://www.devze.com 2023-02-19 09:51 出处:网络
I left some code out for brevity... int id = Convert.ToInt32(Page.RouteData.Values[\"id\"]); var q = db.Categories.SingleOrDefault(x => x.categoryID == id);

I left some code out for brevity...

int id = Convert.ToInt32(Page.RouteData.Values["id"]);
var q = db.Categories.SingleOrDefault(x => x.categoryID == id);

ddlCategory.SelectedValue = q.parentID == 0 ? 0 : id.ToString();

I get the error:

Type of conditional expression cannot be determined bec开发者_如何转开发ause there is no implicit conversion between 'int' and 'string' (It's talking about the id.ToString() piece.)

I tried Convert.ToString() and I tried putting (string) infront of id but that didn't work.


Because the two return values of the ternary are not of the same type -- one is int and the other is string. The compiler cannot deduce what the ternary expression's return type is.

Solution: Return the same type from both branches, or cast one of them to a base of the other. object will do fine.


Because your are trying to make the ternary operator evaluate to either an int (0) or a string (id.ToString()). Replace the 0 with "0".

0

精彩评论

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