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 = Convert.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>
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With