user788487 user788487 - 1 year ago 76
C# Question

Checking for nulls in an integer data type

I have a line that is giving an error:

Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'int'

param[0].Value = form_request_id == null ? DBNull.Value.ToString() : form_request_id;

however, form_request_id is an int

How do I check for nulls in an int data type?

Answer Source

Your immediate problem isn't that you're checking for nulls in form_request_id (which will actually always evaluate to false since you really need to use an int? for the value to actually be null).

The real problem is that both sides of your conditional expression return different types (one is string and the other is int).

Since the param[0].Value should really be different types based on the're not going to be able to use the shortcut statement here. You'll have to spell it out the long way:

if(form_request_id == null)
    param[0].Value = DBNull.Value;
    param[0].Value = form_request_id;

As I mentioned before, you still need to use int? rather than int so that your variable can appropriately hold a null value. When you do that, you shouldn't even need the statement anymore because the database provider will see a null value and substitute DBNull.Value for you behind the scenes. The code would simply be:

param[0].Value = form_request_id;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download