Michael Z
Michael Z

Reputation: 3993

Nullable parameter checking

Let's suppose I write public API in C#:

public void Method(object param) 
{
    if(param == null) 
    {
        throw new ArgumentNullException("Specified 'param' can not be null");
    }

// ... other business logic
}

I wonder is there any guarantees that I do not need to check parameter for null value if I have NOT nullable parameter (object? param) as method parameter? In other words is above example's checking for null redundant?

Upvotes: 0

Views: 320

Answers (4)

Msonic
Msonic

Reputation: 1456

It isn't redundant, because a variable of type object can be set to null, because it's a reference type. The type object? doesn't exist.

Upvotes: 0

Tigran
Tigran

Reputation: 62246

If this is redundant or not, can not be defined in the scope of this single method, but inside your program domain. Where this method used? What does it supose to do? What should happen in the program when it fails ?

Answering this question you will find yourself answering your own.

Upvotes: 0

user743382
user743382

Reputation:

No, reference types are always nullable. Just try it: call Method(null); and you will get a runtime ArgumentNullException, exactly where you throw it in the code. You don't get a compiler error, because null is a valid value for reference types.

For value types it's a different story. If you have a parameter of type int, it cannot be null. In fact, if (i == null) won't even be accepted by the compiler.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754665

If your parameter is typed to a reference type then it's always possible for null to be passed as a value. Hence this check, when only considering Method is never redundant.

It is possible for a context specific analysis of a given method to prove null is never used. For example

sealed class Example {
  void Method(object p) {
    ...
  }
  void Other() {
    Method("hello");
  }
}

In this specific context you can demonstrate that Method can't ever be called with a null value (excluding of course reflection based invocation). But this type of determination can only be done with context specific analysis

Upvotes: 1

Related Questions