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

前端 未结 10 1537
野性不改
野性不改 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:32

    Check the declaration of your variable. It must be like that

    public Nullable<int> x {get; set;}
    public Nullable<int> y {get; set;}
    public Nullable<int> z {get { return x*y;} }
    

    I hope it is useful for you

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

    Your method's return type is int and you're trying to return an int?.

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

    Well you're casting OrdersPerHour to an int?

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

    Yet your method signature is int:

    static int OrdersPerHour(string User)
    

    The two have to match.


    Also a quick suggestion -> Use parameters in your query, something like:

    string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > ? AND User = ? AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered')";
    OleDbCommand dbcommand = new OleDbCommand(query, conn);
    dbcommand.Parameters.Add(curTime.AddHours(-1));
    dbcommand.Parameters.Add(User);
    
    0 讨论(0)
  • 2021-01-03 20:38

    The first problem encountered with your code is the message

    Local variable OrdersPerHour might not be initialized before accessing.

    It happens because in the case where your database query would throw an exception, the value might not be set to something (you have an empty catch clause).

    To fix this, set the value to what you'd want to have if the query fails, which is probably 0 :

    int? OrdersPerHour = 0;

    Once this is fixed, now there's the error you're posting about. This happens because your method signature declares you are returning an int, but you are in fact returning a nullable int, int?, variable.

    So to get the int part of your int?, you can use the .Value property:

    return OrdersPerHour.Value;
    

    However, if you declared your OrdersPerHour to be null at start instead of 0, the value can be null so a proper validation before returning is probably needed (Throw a more specific exception, for example).

    To do so, you can use the HasValue property to be sure you're having a value before returning it:

    if (OrdersPerHour.HasValue){
        return OrdersPerHour.Value;
    }
    else{
        // Handle the case here
    }
    

    As a side note, since you're coding in C# it would be better if you followed C#'s conventions. Your parameter and variables should be in camelCase, not PascalCase. So User and OrdersPerHour would be user and ordersPerHour.

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