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

For C# 7

In C# 7, throw becomes 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:

public static T ThrowException<T>()
{
    throw new Exception(); // Could pass this in
}

And then:

return command.ExecuteScalar() as int? ?? ThrowException<int?>();

I really don’t recommend that you do that though… it’s pretty horrible and unidiomatic.

How about an extension method:

public static T ThrowIfNull(this T value)
{
    if (value == null)
    {
        throw new Exception(); // Use a better exception of course
    }
    return value;
}

Then:

return (command.ExecuteScalar() as int?).ThrowIfNull();

Yet another alternative (again an extension method):

public static T? CastOrThrow<T>(this object x) 
    where T : struct
{
    T? ret = x as T?;
    if (ret == null)
    {
        throw new Exception(); // Again, get a better exception
    }
    return ret;
}

Call with:

return command.ExecuteScalar().CastOrThrow<int>();

It’s somewhat ugly because you can’t specify int? as the type argument…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)