Use c# Null-Coalescing Operator with an int
I'm trying to use the null-coalescing operator on an int. It works when I use it on strings
UserProfile.Name = dr["Name"].ToString()??"";
When I try to use it on an int like this
UserProfile.BoardID = Conve开发者_开发知识库rt.ToInt32(dr["BoardID"])??default(int);
I get this error message
Operator '??' cannot be applied to operands of type 'int' and 'int'
I found this blog post where it is used http://davidhayden.com/blog/dave/archive/2006/07/05/NullCoalescingOperator.aspx with the int data type. Can anyone tell what I'm doing wrong?
I suspect what you're really trying to do is set BoardID to 0 if dr["BoardID"] is NULL from the database. Because if dr["BoardID"] IS null, Convert.ToInt32 will fail. Try this:
UserProfile.BoardID = (dr["BoardID"] is DbNull) ? 0 : Convert.ToInt32(dr["BoardID"]);
An int
is never null
, so applying ??
to it makes no sense.
One way to achieve what you want is TryParse
:
int i;
if(!int.TryParse(s, out i))
{
i = 0;
}
Or since you want to get 0
or default(int)
you can throw out the if, since the output parameter of TryParse
in the error case is already default(int)
:
int i;
int.TryParse(s, out i);
The article you linked doesn't have int
on the left side of ??
but int?
. This is a shortcut for Nullable<int>
, which supports null
thus ??
makes sense with it.
int? count = null;
int amount = count ?? default(int); //count is `int?` here and can be null
Yeah, of course... because int
can't be null.
It only has 32 bits, and all combinations represent a valid integer.
Use int?
instead, if you want nullability. (It's shorthand for System.Nullable<int>
.)
In your link ??
operator is applied to Nullable<int>
(int?
) which can have null value.
Null-coalescing operator works in the following way:
If the value on the left of the operator is null then return the value on the right of the operator. Int is value type, so it can never have null value. That is why you get the error.
In the example you linked the lines with the ??
operator on int
are:
int? count = null;
int amount = count ?? default(int);
Hence in that example int is nullable
You can only use the null-coalescing operator on reference types, or nullable value types. For example: string
, or int?
See http://msdn.microsoft.com/en-us/library/ms173224.aspx
精彩评论