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

前端 未结 2 1962
梦如初夏
梦如初夏 2021-01-24 04:57

I left some code out for brevity...

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

         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-24 05:28

    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.

提交回复
热议问题