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

前端 未结 10 1536
野性不改
野性不改 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.

    0 讨论(0)
  • 2021-01-03 20:18

    simple

    (i == null) ? i.Value : 0;
    
    0 讨论(0)
  • 2021-01-03 20:24
    Int32 OrdersPerHour = 0;
    OrdersPerHour = Convert.ToInt32(dbcommand.ExecuteScalar());
    
    0 讨论(0)
  • 2021-01-03 20:29

    OrdersPerHour = (int?)dbcommand.ExecuteScalar();

    This statement should be typed as, OrdersPerHour = (int)dbcommand.ExecuteScalar();

    0 讨论(0)
  • 2021-01-03 20:31

    You can change the last line to following (assuming you want to return 0 when there is nothing in db):

    return OrdersPerHour == null ? 0 : OrdersPerHour.Value;
    
    0 讨论(0)
  • 2021-01-03 20:32

    this is because the return type of your method is int and OrdersPerHour is int? (nullable) , you can solve this by returning its value like below:

    return OrdersPerHour.Value
    

    also check if its not null to avoid exception like as below:

    if(OrdersPerHour != null)
    {
    
        return OrdersPerHour.Value;
    
    }
    else
    {
    
      return 0; // depends on your choice
    
    }
    

    but in this case you will have to return some other value in the else part or after the if part otherwise compiler will flag an error that not all paths of code return value.

    0 讨论(0)
提交回复
热议问题