Alex
Alex

Reputation: 134

Reference type null checking

Should I check every single reference type argument passed to a method that it is not null?

Option 1, without checking:

public void Foo(A a, B b)
{
    a.DoSomething();
    b.DoSomething();
}

Option 2, with checking:

public void Foo(A a, B b)
{
    if (a is null)
        throw new ArgumentNullException();

    if (b is null)
        throw new ArgumentNullException();

    a.DoSomething();
    b.DoSomething();
}

I also have tried something like that, but it doesn't work at all

public void Foo(A a, B b)
{
    Contract.Requires(a is not null);
    Contract.Requires(b is not null);

    a.DoSomething();
    b.DoSomething();
}

Upvotes: 0

Views: 206

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156504

If you don't expect the value to be nullable, you definitely want to throw an argument exception when it is null. But that doesn't mean you have to add a bunch of extra code.

I'm personally a fan of enabling Nullable Reference Types, turning nullable warnings into compiler errors, and enabling Fody NullGuard on whatever types/assemblies/projects you want to add this behavior to. NullGuard will add code to your compiled assembly to throw exceptions if non-null arguments or return values are null.

Upvotes: 2

Related Questions