Cannot implicitly convert type 'int?' to 'int'.

前端 未结 10 1586
野性不改
野性不改 2021-01-03 19:34

I\'m getting the error \"Cannot implicitly convert type \'int?\' to \'int\'. An explicit conversion exists (are you missing a cast?)\" on my OrdersPerHour at the return line

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 20:14

    If you're concerned with the possible null return value, you can also run something like this:

    int ordersPerHour;  // can't be int? as it's different from method signature
    // ... do stuff ... //
    ordersPerHour = (dbcommand.ExecuteScalar() as int?).GetValueOrDefault();
    

    This way you'll deal with the potential unexpected results and can also provide a default value to the expression, by entering .GetValueOrDefault(-1) or something more meaningful to you.

提交回复
热议问题