Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = 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?

like image 519
Ronald McDonald Avatar asked Jul 08 '11 16:07

Ronald McDonald


3 Answers

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"]);
like image 66
n8wrl Avatar answered Oct 05 '22 03:10

n8wrl


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
like image 25
CodesInChaos Avatar answered Oct 05 '22 01:10

CodesInChaos


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>.)

like image 44
user541686 Avatar answered Oct 05 '22 03:10

user541686