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?
For C# 7
In C# 7,
throwbecomes an expression, so it’s fine to use exactly the code described in the question.For C# 6 and earlier
You can’t do that directly in C# 6 and earlier – the second operand of ?? needs to be an expression, not a throw statement.
There are a few alternatives if you’re really just trying to find an option which is concise:
You could write:
And then:
I really don’t recommend that you do that though… it’s pretty horrible and unidiomatic.
How about an extension method:
Then:
Yet another alternative (again an extension method):
Call with:
It’s somewhat ugly because you can’t specify
int?as the type argument…