Throwing ArgumentNullException - c#

Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it's a fatal error and an exception should be thrown. Is it worth it for me to code something like this (keeping in mind this is a trivial example):
void someMethod(SomeClass x)
{
if (x == null){
throw new ArgumentNullException("someMethod received a null argument!");
}
x.doSomething();
}
Or is it safe for me to just rely on it throwing NullException when it calls x.doSomething()?
Secondly, suppose that someMethod is a constructor and x won't be used until another method is called. Should I throw the exception immediately or wait until x is needed and throw the exception then?

I prefer the ArgumentNullException over the NullReferenceException that not checking the argument would provide. In general, my preference is to always check for nullity before trying to invoke a method on a potentially null object.
If the method is a constructor, then it would depend on a couple of different factors: is there also a public setter for the property and how likely is it that the object will actually be used. If there is a public setter, then not providing a valid instance via the constructor would be reasonable and should not result in an exception.
If there is no public setter and it is possible to use the containing object without referencing the injected object, you may want to defer the checking/exception until its use is attempted. I would think that the general case, though, would be that injected object is essential to the functioning of the instance and thus an ArgumentNull exception is perfectly reasonable since the instance can't function without it.

I always follow the practice of fail fast. If your method is dependent on X and you understand X might be passed in null, null check it and raise the exception immediately instead of prolonging the point of failure.
2016 update:
Real world example. I strongly recommend the usage of JetBrains Annotations.
[Pure]
public static object Call([NotNull] Type declaringType,
[NotNull] string methodName,
[CanBeNull] object instance)
{
if (declaringType == null) throw new ArgumentNullException(nameof(declaringType));
if (methodName == null) throw new ArgumentNullException(nameof(methodName));
Guard statements have been vastly improved with C# 6 providing the nameof operator.

I prefer the explicit exception, for these reasons:
If the method has more than one SomeClass argument it gives you the opportunity to say which one it is (everything else is available in the call stack).
What if you do something that may have a side effect before referencing x?

No excuse not to make the check these days. C# has moved on and you can do this very neatly using a discard and a null coalescing operator:
_ = declaringType ?? throw new ArgumentNullException(nameof(declaringType));
_ = methodname ?? throw new ArgumentNullException(nameof(methodName));

I agree with the idea of failing fast - however it is wise to know why failing fast is practical. Consider this example:
void someMethod(SomeClass x)
{
x.Property.doSomething();
}
If you rely on the NullReferenceException to tell you that something was wrong, how will you know what was null? The stack trace will only give you a line number, not which reference was null. In this example x or x.Property could both have been null and without failing fast with aggressive checking beforehand, you will not know which it is.

I'd prefer the parameter check with the explicit ArgumentNullException, too.
Looking at the metadata:
//
// Summary:
// Initializes a new instance of the System.ArgumentNullException class with
// the name of the parameter that causes this exception.
//
// Parameters:
// paramName:
// The name of the parameter that caused the exception.
public ArgumentNullException(string paramName);
You can see, that the string should be the name of the parameter, that is null, and so give the developer a hint on what is going wrong.

I strongly agree with #tvanfosson. Adding to his answer, with .net 6 it’s very easy to throw the ArgumentNullException.
ArgumentNullException.ThrowIfNull(object);
Here’s the official documentation.

You should explicitly throw an ArgumentNullException if you are expecting the input to not be null. You might want to write a class called Guard that provides helper methods for this. So your code will be:
void someMethod(SomeClass x, SomeClass y)
{
Guard.NotNull(x,"x","someMethod received a null x argument!");
Guard.NotNull(y,"y","someMethod received a null y argument!");
x.doSomething();
y.doSomething();
}
The NonNull method would do the nullity check and throw a NullArgumentException with the error message specified in the call.

It is better to throw the ArgumentNullException sooner rather than later. If you throw it, you can provide more helpful information on the problem than a NullReferenceException.

Do it explicitly if you do not want a Null value. Otherwise, when someone else look at your code, they will think that passing a Null value is acceptable.
Do it as early as you can. This way, you do not propagate the "wrong" behavior of having a Null when it's not supposed to.

If you program defensively you should fail fast. So check your inputs and error out at the beginning of your code. You should be nice to your caller and give them the most descriptive error message you can.

I'll probably be downvoted for this, but I think completely different.
What about following a good practice called "never pass null" and remove the ugly exception checking?
If the parameter is an object, DO NOT PASS NULL. Also, DO NOT RETURN NULL. You can even use the Null object pattern to help with that.
If it's optional, use default values (if your language supports them) or create an overload.
Much cleaner than ugly exceptions.

Since .NET 6 you can throw the argument null exception in one line for instance:
int? foo = null;
ArgumentNullException.ThrowIfNull(foo);
This will check if foo is null and throw an error. You can pass a second parameter to set the parameter name, but this is not recommended.
https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception.throwifnull?view=net-6.0

You can use syntax like the following to not just throw an ArgumentNullException but have that exception name the parameter as part of its error text as well. E.g.;
void SomeMethod(SomeObject someObject)
{
Throw.IfArgNull(() => someObject);
//... do more stuff
}
The class used to raise the exception is;
public static class Throw
{
public static void IfArgNull<T>(Expression<Func<T>> arg)
{
if (arg == null)
{
throw new ArgumentNullException(nameof(arg), "There is no expression with which to test the object's value.");
}
// get the variable name of the argument
MemberExpression metaData = arg.Body as MemberExpression;
if (metaData == null)
{
throw new ArgumentException("Unable to retrieve the name of the object being tested.", nameof(arg));
}
// can the data type be null at all
string argName = metaData.Member.Name;
Type type = typeof(T);
if (type.IsValueType && Nullable.GetUnderlyingType(type) == null)
{
throw new ArgumentException("The expression does not specify a nullible type.", argName);
}
// get the value and check for null
if (arg.Compile()() == null)
{
throw new ArgumentNullException(argName);
}
}
}

All code examples use error prone IF clause, where one use equal operator ==.
What happen, if type override == ?
On C# 7 and greater, use constant pattern matching.
example:
if (something is null)
{
throw new ArgumentNullException(nameof(something), "Can't be null.");
}

Related

Can an object set it self to null?

In C#, is it possible for an object to do suicide, that is set it self to null ?
this=null; didn't work....
The reason for wanting such ting is that if e.g. the object gets data in via constructor that is not good (for any reason), then it might be better off being null than rubbish.
A status flag is a workaround, but that is my second best alternative.
I suggest you throw an ArgumentException from the constructor in case you receive problematic data from the caller. Then catch that in the calling code.
No the object cannot set itself into null, it's the reference that can be set to null.
Just throw an ArgumentException insteed
If the object needs external data in order to complete its construction and gets something unusable (or no data at all) then what you need to do is throw an appropriate exception.
Changing the value of this is illegal, and even if it were not it would not offer any benefit: the caller still has to determine what happened during construction.
You should throw an exception in the constructor; this will prevent the object from being created all together:
class MyClass {
public MyClass(string value) {
if (value == null)
throw new ArgumentNullException("value");
...
}
}
In C++ you can play with this how you want.
In C# - only in restricted way. For example, you can assign struct's, but not the class' this to something

return (Type)Instance OR return instance as Type

What's the difference between (fictious):
public Test GetTest()
{
Object obj = new Test();
return (Test)obj;
}
And
public Test GetTest()
{
Object obj = new Test();
return obj as Test;
}
Is it right that the first approach throws an exception if obj == null? And the second doesn't?
No; both approaches will succeed and return null if obj is null. The difference lies in what happens if obj is not an instance of Test: the first approach will throw an exception, while the second one will succeed and return null.
In other words: Use the first approach if you know that your object is a Test or if you don't know what it is, but you want an exception if it is not a Test. Use the second approach if you don't know what your object is, but you just want a peaceful null if it is not a Test. You can also use as for type checking if you intend to do something special if the type check succeeds:
var t = obj as Test;
if (t != null) {
...
}
instead of:
if (obj is Test) {
var t = (Test)obj;
...
}
In that way, you don't need to repeat the type name, although the second form is probably clearer and avoids leaking t to the rest of the scope.
Also, see #il_guru's post for some additional caveats related to as.
Neither will ever throw an exception on the cast line. In C#, if new returns (since the constructor didn't throw an exception) then obj is (pretty much, modulo cases where your memory is being corrupted somehow) guaranteed to be good memory of the newed type. That means, among other things, that obj will never be assigned null.
Given that, I would prefer the C-style cast (i.e. (Test)obj) since it's certain to work, and is a bit clearer to read.
In general, the difference between the casts is that C-style will throw an exception if you've gotten the type wrong, while as just returns null. But again, neither of those will happen in the code you've provided.
In addition to what was said about NULL in a previous answer (an explicit cast to null does not raise an exception), the as cast has some limitation; as stated on MSDN
Note that the as operator only performs reference conversions and
boxing conversions. The as operator cannot perform other conversions,
such as user-defined conversions, which should instead be performed by
using cast expressions.

Throwing ArgumentNullException

Is it a good idea to throw ArgumentNullException() when having a null value? This thread doesn't mention the most obvious exception to throw on a null.
Thanks
ArgumentNullException should only be used when the parameter to a method is found to be null:
public void MyMethod(MyClass cannotBeNull)
{
if (cannotBeNull == null)
{
throw new ArgumentNullException("cannotBeNull");
}
// Do something useful
}
Actually you are reading it backwards, the other scenerio posses the situation:
If I am expecting a null value and get a defined value
If you look at the MSDN: ArgumentNullException it is specifically for
The exception that is thrown when a null reference (Nothing in Visual
Basic) is passed to a method that does
not accept it as a valid argument.
I am expecting a null and I get something
vs.
I am expecting something and I get null
That said, there is no reason you can not, or should not, create your own
public class IWantANullException:Exception
and throw it around in what ever way you wish.

null target of extension method

public static IFoo Bar<T>(this IFoo target, ...)
{
// I'm curious about how useful this check is.
if (target == null) throw new ArgumentNullException("target");
...
}
(1) The code above seems strange to me because I feel like in any case the calling code would be the one to check that. Is there some subtlety to extension methods in this area that applies?
(2) Is there a legitimate pattern that leverages the fact that the target can be null? I ask this as a consequence of wondering why calling an extension method on a null reference wouldn't generate the runtime exception the same way as if you called an instance method on a null reference.
Consider that null can be an argument to a method. Consider also that the extension method foo.Bar<int>(); is really just syntactic sugar for IFooExtensions.Bar<int>(foo); and you will see that, yes, the argument can indeed be null so if you're doing something with the argument, it may certainly be appropriate to test it for null (or simply let a NullReferenceException be thrown, take your pick).
Note: You would not get an exception merely by calling it with a null referenced object, because remember that the method does not actually belong to the object. You only get the exception if (a) you purposefully throw one yourself or (b) the method body actually causes it by trying to work with the instance that is null.
(2) Is there a legitimate pattern that
leverages the fact that the target can
be null? I ask this as a consequence
of wondering why calling an extension
method on a null reference wouldn't
generate the runtime exception the
same way as if you called an instance
method on a null reference.
Well, here's one use of it.
public static class UtilityExtensions
{
public static void ThrowIfNull( this object obj, string argName )
{
if ( obj == null )
{
throw new ArgumentNullException( argName );
}
}
}
Now you can write null checks easily and on one line (helpful if your coding convention forces you to use braces with all if statements).
public void Foo(string bar)
{
bar.ThrowIfNull("bar");
// ...
}
Whether or not you consider that a "legitimate" pattern is up to you, but I'd be very sad if the runtime was changed to make extension method invocations on null references throw exceptions.
Since extension methods really are only syntactic sugar for calling a static method with the object as the first parameter, I don't see why null for this parameter value shouldn't be allowed.

When to check for nulls

This is kinda an open ended question but I'm trying to sharpen my skills with good practices in exception handling specifically when to check for nulls in general.
I know mostly when to check for nulls but I have to say half the time I don't and that's bothering to me. I know ints cannot be set to null unless you use a nullable int. I know strings can be set to null OR empty hence you can check for IsNullOrEmpty.
Obviously in constructors you want to add your explicit checks there also. That's a given. And that I think you should check for null anytime you're passing in an array, generic object, or other objects into a method that can be set to null basically right?
But there is more here to exception handling. For instance I don't know when to always check and throw a null ref exception explicitely in code. If I've got incoming params, usually it's pretty straight forward but there are always cases where I ask myself, is an explicit null throw needed?
I don't really have specific examples but wondering if there's a good reference out there that really talks about exception handling in reference to when to throw them (inside methods, classes, you name it).
You shouldn't throw NullReferenceException. If it is an argument that is null throw ArgumentNullException instead.
I prefer to check for null for all reference types parameters of public/protected methods. For private methods, you may omit the check if you're sure all calls will always have valid data.
Unless you're using Code Contracts, I'd say it's good practice to check arguments for any public/protected member - as well as explicitly documenting whether they can or can't be null. For private/internal methods it becomes a matter of verifying your own code rather than someone else's... it's a judgement call at that point.
I sometimes use a helper extension method for this, so I can write:
public void Foo(string x, string y, string z)
{
x.ThrowIfNull("x");
y.ThrowIfNull("y");
// Don't check z - it's allowed to be null
// Method body here
}
ThrowIfNull will throw an ArgumentNullException with the appropriate name.
By checking explicitly before you make any other calls, you know that if an exception is thrown, nothing else will have happened so you won't have corrupted state.
I admit I'll omit such checks where I know for certain that the first call will do the same checks - e.g. if it's one overload piggybacking onto another.
With Code Contracts, I'd write:
public void Foo(string x, string y, string z)
{
Contract.Requires(x != null);
Contract.Requires(y != null);
// Rest of method here
}
This will throw a ContractException instead of ArgumentNullException, but all the information is still present and no-one should be catching ArgumentNullException explicitly anyway (other than possibly to cope with third party badness).
Of course the decision of whether you should allow null values is an entirely different matter. That depends entirely on the situation. Preventing nulls from ever entering your world does make some things easier, but at the same time nulls can be useful in their own right.
My rules of thumb for when to check for nulls are:
Always check the arguments passed to a public/protected method of any class.
Always check the arguments to constructors and initialize methods.
Always check the arguments in an indexer or property setter.
Always check the arguments to methods that are interface implementations.
With multiple overloads, try to put all argument preconditions in a single method that other overloads delegate to.
Early notification of null arguments (closer to the point of error) are much better than random NullReferenceExceptions that occur far from the point of the error.
You can use utility methods to clean up the typical if( arg == null ) throw new ArgumentNullException(...); constructs. You may also want to look into code contracts in C# 4.0 as a way to improve your code. Code contracts perform both static and runtime checks which can help identify problems even at compile time.
In general, writing preconditions for methods is a time consuming (and therefore often omitted) practice. However, the benefit to this type of defensive coding is in the hours of potentially saved time debugging red herrings that occur because you didn't validate your inputs.
As a side note, ReSharper is a good tool for identifying potential access to arguments or local members that may be null at runtime.
The earlier the better. The sooner you catch the (invalid) null, the less likely you'll be throwing out in the middle of some critical process. One other thing to consider is using your properties (setters) to centralize your validation. Often I reference my properties in the constructor, so I get good reuse on that validation.
class A
{
private string _Name
public string Name
{
get { return _Name; }
set
{
if (value == null)
throw new ArgumentNullException("Name");
_Name = value;
}
}
public A(string name)
{
//Note the use of property with built in validation
Name = name;
}
}
Depends on your type of method/api/library/framework. I think its ok for private methods that they dont check for null values unless they are kind of assertion methods.
If you programm defensive and litter your code with "not null"-tests or "if"-statements your code will be unreadable.
Define the areas where a client can mess up your code by submitting wrong/empty/null arguments. If you know where, you can draw the line where to do your null checks. Do it at your api entry points just like the security works in real life.
Imagine you would be bothered every minute to show your ticket in a cinema every movie would suck.
I prefer using static template methods for checking input constraints. the general format for this would be something like:
static class Check {
public static T NotNull(T arg) {
if( arg == null ) throw new ArgumentNullException();
}
}
The benefit to using this is that your method or constructor can now wrap the first use of the argument with Check.NotNull() as exampled here:
this.instanceMember = Check.NotNull(myArgument);
When I get to .Net 4, I'll likely convert to code contracts, but until then this works. BTW, You can find a more complete definition of the Check class I use at the following url:
http://csharptest.net/browse/src/Shared/Check.cs

Categories