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

前端 未结 5 1990
挽巷
挽巷 2020-12-17 08:43

I have a number of methods doing next:

var result = command.ExecuteScalar() as Int32?;
if(result.HasValue)
{
   return result.Value;
}
else
{
   throw new Ex         


        
5条回答
  •  [愿得一人]
    2020-12-17 09:15

    The reason you can't do:

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

    Is because throwing an exception is a statement, not an expression.

    If you're just looking to shorten the code a little bit, perhaps this:

    var result = command.ExecuteScalar() as Int32?;
    if(result.HasValue) return result;
    throw new Exception();
    

    No need for the else.

提交回复
热议问题