Olivier Pons
Olivier Pons

Reputation: 15778

Automatically raising an exception if value is null

In my class I've done this:

private void RaiseExceptionIfNull(object o, string error)
{
    if (o == null) {
        throw new System.NullReferenceException(error + " is null " +
                                                "(should never be null)");
    }
}

And then in all my methods, I'm doing stuff like this:

RaiseExceptionIfNull(cbAjaxFinished, "Callback Ajax Finished");
RaiseExceptionIfNull(j, "Result conversion");

... all of this because I'd like to raise an exception if value is null in one line (with clean code).

I was wondering if there's already a way to raise an exception like I do, but in C# (I'm a newbie in this area) (kind of "assert() in C", but with custom exception).

Upvotes: 0

Views: 148

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

In your case, I would throw an ArgumentNullException instead of using NullReferenceException since your are checking for an argument to be invalid because it's null. With extension methods, you can achieve a one-liner check very easily:

// value types should be excluded as they can't be null
// hence the "where T : class" clause
internal static void ThrowIfNull<T>(this T obj, String parameterName) where T : class
{
    if (obj == null)
        throw new ArgumentNullException(parameterName);
}

Then, in your methods use the extension as follows:

public void MyFunc(Object obj)
{
    obj.ThrowIfNull(nameof(obj));

    // Your implementation...
}

Upvotes: 1

Related Questions