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?
No, reference types are always nullable. Just try it: call
Method(null);and you will get a runtimeArgumentNullException, 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.