Checking constructor parameter for null before calling base

You can do it with something like this:

public TheInheritor(TheArgument theArgument)
    : base(ConvertToId(theArgument))
{
}

private static int ConvertToId(TheArgument theArgument)
{
    if (theArgument == null)
    {
        throw new ArgumentNullException("theArgument");
    }
    return theArgument.Id;
}

Or more generally, something like this:

public TheInheritor(TheArgument theArgument)
    : base(Preconditions.CheckNotNull(theArgument).Id)
{
}

where Preconditions is a utility class elsewhere, like this:

public static class Preconditions
{
    public static T CheckNotNull<T>(T value) where T : class
    {
        if (value == null)
        {
            throw new ArgumentNullException();
        }
        return value;
    }
}

(This loses the argument name, of course, but you could pass that in as well if necessary.)

Leave a Comment

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