开发者

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?


int is a value type and can not be null - it will default to 0.

You can make an int nullable in two ways:

int? nullableInt = null;

Or,

Nullable<int> nullableInt = null;

Both options are fundamentally the same at the lowest level, I believe, with the former being shorthand for the latter.

This essentially gives the type a wrapper that exposes two useful properties, HasValue and HasValue. HasValue can be used to check whether the contained instance has a value other than null, Value allows you to retrieve the value.

Check the MSDN page on Nullable<T> for more information and examples.

As pointed out by @Justin Niessner, though, the error message you get relates not to this problem, but to the fact that form_request_id and DBNull.Value.ToString() are different types. If form_request_id is not null, then try calling ToString on that (or using some other mechanism to assign a value of desired, differing types.


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 condition...you'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;
else
    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;


param[0].Value = nullableInt ?? DBNull.Value;


Probably type of form_request_id is not int but

int?//or
Nullable<int>


You need to define you int variable as a Nullable type and in order to check if it's null or not you need to use HasValue. In order to access the value of your nullable variable use x.Value

int? x = 10;

if (x.HasValue)
{
   //code here
}


an int type cannot be null. Default value of an int is 0 so you can check against 0 if you want to make sure its value has been set.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜