Alex Rivera | Logout

Is it possible to use operator ?? and throw new Exception()?

Asked 2009-11-19T11:50:36.993
34

I have a number of methods doing next:

var result = command.ExecuteScalar() as Int32?;
if(result.HasValue)
{
   return result.Value;
}
else
{
   throw new Exception(); // just an example, in my code I throw my own exception
}

I wish I could use operator ?? like this:

return command.ExecuteScalar() as Int32? ?? throw new Exception();

but it generates a compilation error.

Is it possible to rewrite my code or there is only one way to do that?

Edit
Report

1 Answer

2

You're not going to be able to throw an exception on the right side of the null coalescing operator. The reason behind this is that that the right side of the operator needs to be an expression, not a statement.

The null coalescing operator works like so: if the left value of the operator is null, return it; otherwise, return what's on the right of the operator. The throw keyword doesn't return a value; hence, it can't be used on the right side of the operator.

answered 2009-11-19T11:54:19.253

Your Answer