Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; } 
like image 369
MaylorTaylor Avatar asked May 28 '13 17:05

MaylorTaylor


People also ask

What is the use of INT in C#?

int is a keyword that is used to declare a variable which can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of System. Int32.


2 Answers

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); 
like image 189
Dimitar Dimitrov Avatar answered Sep 24 '22 00:09

Dimitar Dimitrov


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.

like image 29
tariq Avatar answered Sep 26 '22 00:09

tariq