Cannot implicitly convert type 'int?' to 'int'.
Asked Answered
W

10

35

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. I'm not sure why because my C# skills are not that advanced. Any help would be appreciated.

static int OrdersPerHour(string User)
{
    int? OrdersPerHour;
    OleDbConnection conn = new OleDbConnection(strAccessConn);
    DateTime curTime = DateTime.Now;        

    try
    {
        string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > #" + curTime.AddHours(-1) + "# AND User = '" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";
        OleDbCommand dbcommand = new OleDbCommand(query, conn);
        dbcommand.Connection.Open();
        dbcommand.CommandType = CommandType.Text;
        OrdersPerHour = (int?)dbcommand.ExecuteScalar();

        Console.WriteLine("Orders per hour for " + User + " is " + OrdersPerHour);            
    }
    catch (OleDbException ex)
    {

    }
    finally
    {
        conn.Close();
    }
    return OrdersPerHour;
}
Weighting answered 28/5, 2013 at 17:42 Comment(0)
A
29

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);
Armchair answered 28/5, 2013 at 17:44 Comment(3)
I understand my mistake on this part now. But after making those changes, I am getting "User of unassigned local variable 'OrdersPerHour' at the return line.Weighting
@Weighting Change int? OrdersPerHour; to int OrdersPerHour = 0;, should take care of it.Armchair
OK that fixed me right up; however, now i'm getting another problem. #16745010Weighting
C
23

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.

Colossian answered 28/5, 2013 at 17:50 Comment(0)
L
6
Int32 OrdersPerHour = 0;
OrdersPerHour = Convert.ToInt32(dbcommand.ExecuteScalar());
Loanloanda answered 19/7, 2013 at 7:6 Comment(0)
F
4

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.

Fletcherfletcherism answered 28/5, 2013 at 17:49 Comment(0)
T
3

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

Theurgy answered 22/5, 2020 at 11:15 Comment(0)
A
2

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;
Appalling answered 28/5, 2013 at 17:48 Comment(0)
C
1

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

Cutch answered 28/5, 2013 at 17:45 Comment(0)
O
1

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

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

Osteotomy answered 28/5, 2013 at 17:51 Comment(0)
B
1

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.

Burdock answered 17/10, 2017 at 10:16 Comment(0)
P
-1

simple

(i == null) ? i.Value : 0;
Phonolite answered 9/9, 2015 at 6:59 Comment(2)
While this may theoretically work, it doesn't explain how it works to anybody. Saying "simple" isn't really enough.Goatsbeard
.. It definitely won't work. You have a NullReferenceException when i == null and returns 0 when it isn't.Goatsbeard

© 2022 - 2024 — McMap. All rights reserved.