Can an object set it self to null? - c#

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

Related

Is there a way to have a C# class handle its own null reference exceptions

Question
I'd like to have a class that is able to handle a null reference of itself. How can I do this? Extension methods are the only way I can think to do this but thought I'd ask in case there was some nifty thing I didn't know about C#.
Example
I have a class called User with a property called IsAuthorized.
When User is properly instantiated IsAuthorized has an implementation. However, when my User reference contains null I'd like a call to IsAuthorized to return false instead of exploding.
Solution
Lot's of good answers. I ended up using three of them to solve my problem.
I used the Null Object design pattern suggested by Zaid Masud.
I combined that with Belmiris' suggestion of using struct so I couldn't have a null reference
And got a great explanation for why C# works this way and how I could really solve it from Jon Hanna
Unfortunately I can only pick one of these as my accepted answer so if you are visiting this page you should take the time to up vote all three of these and any of the other excellent answers that were given.
How about a proper Object Oriented solution? This is exactly what the Null Object design pattern is for.
You could extract an IUser interface, have your User object implement this interface, and then create a NullUser object (that also implements IUser) and always returns false on the IsAuthorized property.
Now, modify the consuming code to depend on IUser rather than User. The client code will no longer need a null check.
Code sample below:
public interface IUser
{
// ... other required User method/property signatures
bool IsAuthorized { get; }
}
public class User : IUser
{
// other method/property implementations
public bool IsAuthorized
{
get { // implementation logic here }
}
}
public class NullUser : IUser
{
public bool IsAuthorized
{
get { return false; }
}
}
Now, your code will return an IUser rather than a User and client code will only depend on IUser:
public IUser GetUser()
{
if (condition)
{
return new NullUser(); // never return null anymore, replace with NullUser instead
}
return new User(...);
}
However, when my User reference contains null I'd like IsAuthorized to always return false instead of exploding.
This can only be done if IsAuthorized is a static method, in which case you can check for null. This is why extension methods can do this - they are really just a different syntax for calling a static method.
Calling a method or property, such as IsAuthorized as an instance method requires an instance. Just the act of calling an instance method (including a property getter) on null will trigger the exception. The exception isn't raised by your class, but by the runtime itself when you attempt to use the (null) reference. There is no way around this in C#.
If the variable is null, it means it references no object, therefore is makes no sense (and I think its not technically possible) to handle the null reference inside the class method.
You should guarantee that it is not null, either by checking just before calling "IsAuthorized" or event before.
Edit: Finding an workaround to do that would be a bad thing: it would be confusing for someone to understand the behavior, since it is not the "expected" behavior for the programming language. It could also cause your code to hide some problem (a null value where it should be an object) and create a bug that will be hard to find. That said: it is for sure a bad idea.
The problem isn't with creating such a method at all. It's with calling the method. If you put a test of if(this == null) in your code, that's perfectly valid. I suppose it could be optimised away by the compiler on the basis of it being "impossible" to be hit, but I thankfully it isn't.
However, when you call the method, it'll be done via callvirt, so rather than call the method directly, it will find the version of the method to call for the particular instance just as it would with a virtual method. Since that will fail for null references, your perfectly good self-null-testing method will fail before it is even called.
C# deliberately does this. According to Eric Gunnerson this was because they thought letting you do so would be a bit weird.
I've never understood why letting a .NET language modelled upon C++ do something that is perfectly allowable in both .NET and the C++ compiler produced by the same company,* was considered a bit weird. I've always considered it a bit weird that it wasn't allowed.
You can add something from another language (F# or IL) that calls the class, or use Reflection.Emit to generate a delegate that does so and that'll work fine. For example, the following code will call the version of GetHashCode defined in object (that is, even if GetHashCode was overridden, this doesn't call the override) which is an example of a method that is safe to call on a null instance:
DynamicMethod dynM = new DynamicMethod(string.Empty, typeof(int), new Type[]{typeof(object)}, typeof(object));
ILGenerator ilGen = dynM.GetILGenerator(7);
ilGen.Emit(OpCodes.Ldarg_0);
ilGen.Emit(OpCodes.Call, typeof(object).GetMethod("GetHashCode"));
ilGen.Emit(OpCodes.Ret);
Func<object, int> RootHashCode = (Func<object, int>)dynM.CreateDelegate(typeof(Func<object, int>));
Console.WriteLine(RootHashCode(null));
The one good thing about this, is that you can hold onto RootHashCode so you only need to build it once (say in a static constructor) and then you can use it repeatedly.
This of course is of no value in letting other code call your method through a null reference, for that extension methods like you suggest are your only bet.
It's also worth noting of course, that if you are writing in a language that doesn't have this quirk of C#, that you should offer some alternative means of getting the "default" result for calling on a null reference because C# people can't get it. Much like C# people should avoid case-only differences between public names because some languages can't deal with that.
Edit: A full example of your question's IsAuthorized being called, since votes suggest some people don't believe it can be done (!)
using System;
using System.Reflection.Emit;
using System.Security;
/*We need to either have User allow partially-trusted
callers, or we need to have Program be fully-trusted.
The former is the quicker to do, though the latter is
more likely to be what one would want for real*/
[assembly:AllowPartiallyTrustedCallers]
namespace AllowCallsOnNull
{
public class User
{
public bool IsAuthorized
{
get
{
//Perverse because someone writing in C# should be expected to be friendly to
//C#! This though doesn't apply to someone writing in another language who may
//not know C# has difficulties calling this.
//Still, don't do this:
if(this == null)
{
Console.Error.WriteLine("I don't exist!");
return false;
}
/*Real code to work out if the user is authorised
would go here. We're just going to return true
to demonstrate the point*/
Console.Error.WriteLine("I'm a real boy! I mean, user!");
return true;
}
}
}
class Program
{
public static void Main(string[] args)
{
//Set-up the helper that calls IsAuthorized on a
//User, that may be null.
DynamicMethod dynM = new DynamicMethod(string.Empty, typeof(bool), new Type[]{typeof(User)}, typeof(object));
ILGenerator ilGen = dynM.GetILGenerator(7);
ilGen.Emit(OpCodes.Ldarg_0);
ilGen.Emit(OpCodes.Call, typeof(User).GetProperty("IsAuthorized").GetGetMethod());
ilGen.Emit(OpCodes.Ret);
Func<User, bool> CheckAuthorized = (Func<User, bool>)dynM.CreateDelegate(typeof(Func<User, bool>));
//Now call it, first on null, then on an object
Console.WriteLine(CheckAuthorized(null)); //false
Console.WriteLine(CheckAuthorized(new User()));//true
//Wait for input so the user will actually see this.
Console.ReadKey(true);
}
}
}
Oh, and a real-life practical concern in this. The good thing about C#'s behaviour is that it causes fail-fast on calls on null-references that would fail anyway because they access a field or virtual somewhere in the middle. This means we don't have to worry about whether we're in a null instance when writing calls. If however you want to be bullet-proof in a fully public method (that is, a public method of a public class), then you can't depend on this. If it's vital that step 1 of a method is always followed by step 2, and step 2 would only fail if called on a null instance, then there should be a self-null check. This is rarely going to happen, but it could cause bugs for non-C# users that you'll never be able to reproduce in C# without using the above technique.
*Though, that is specific to their compiler - it's undefined per the C++ standard IIRC.
Can you use a struct instead? Then it should not ever be null.
You can't reference a property if you do not have a valid instance reference. If you want to be able to reference a property even with a null reference and not put the onus of null-checking on the caller, one way is a static method in User:
static bool IsAuthorized(User user)
{
if(user!=null)
{
return user.IsAuthorized;
}
else
{
return false;
}
}
Then, when you want to check your authorization, instead of:
if(thisUser.IsAuthorized)
Do:
if(User.IsAuthorized(thisUser))
The only way this can work is if you use an extension method or other static method to handle the null reference.
NullReferenceExceptions (NullPointerExceptions for the Javaheads; roughly synonymous) occur when code is told to call a method belonging to an object instance that doesn't actually exist. The thing you must keep in mind is that null is not actually any object. A variable of a type can be set to null, but that simply means the variable doesn't reference an instance.
Therein lies the problem; if a variable, regardless of its type (as long as that's a nullable type), is null, then there isn't an instance on which to call the method, and an instance is required for instance methods because that's how the program determines the state of members accessible to the method. If MyClass had a MyField and MyMethod(), and you called MyMethod on a null reference of MyClass, what's the value of MyField?
The solution is usually to move to static scope. Static members (and classes) are guaranteed to have state because they are instantiated once at runtime (usually just-in-time, as in before first reference). Because they always have state, they can always be called and so can be given things to do that may not be able to be done at the instance level. Here's a method you can use in C# to return a value from an object member chain which may otherwise result in an NRE:
public static TOut ValueOrDefault<TIn, TOut>(this TIn input, Func<TIn, TOut> projection,
TOut defaultValue = default(TOut))
{
try
{
var result = projection(input);
if (result == null) result = defaultValue;
return result;
}
catch (NullReferenceException) //most nulls result in one of these.
{
return defaultValue;
}
catch (InvalidOperationException) //Nullable<T>s with no value throw these
{
return defaultValue;
}
}
Usage:
class MyClass {public MyClass2 MyField;}
class MyClass2 {public List<string> MyItems; public int? MyNullableField;}
...
var myClass = null;
//returns 0; myClass is null
var result = myClass.ValueOrDefault(x=>x.MyField.MyItems.Count);
myClass = new MyClass();
//returns 0; MyField is null
result = myClass.ValueOrDefault(x=>x.MyField.MyItems.Count);
myClass.MyField = new MyClass2();
//returns 0; MyItems is null
result = myClass.ValueOrDefault(x=>x.MyField.MyItems.Count);
myClass.MyField.MyItems = new List<string>();
//returns 0, but now that's the actual result of the Count property;
//the entire chain is valid
result = myClass.ValueOrDefault(x=>x.MyField.MyItems.Count);
//returns null, because FirstOrDefault() returns null
var myString = myClass.ValueOrDefault(x=>x.MyField.MyItems.FirstOrDefault());
myClass.MyField.MyItems.Add("A string");
//returns "A string"
myString = myClass.ValueOrDefault(x=>x.MyField.MyItems.FirstOrDefault());
//returns 0, because MyNullableField is null; the exception caught here is not an NRE,
//but an InvalidOperationException
var myValue = myClass.ValueOrDefault(x=>x.MyField.MyNullableField.Value);
While this method has value in situations which would otherwise call for long nested ternary operators to produce something (anything) to show the user or use in a calculation, I do NOT recommend using this pattern to perform actions (void methods). Because no NREs or IOEs will be thrown out, you'll never know if what you asked it to do was actually done. You may be able to get away with a "TryPerformAction()" method which returns true or false, and/or has an output parameter containing the thrown exception (if any). But if you're going to go to that kind of trouble, why not just try/catch the thing yourself?

Checking for Null in Constructor

I'm really trying to figure out the best practices for reusable code that is easily debugged. I have ran into a common practice among developers that I don't quite understand yet.
public MyConstructor(Object myObject)
{
if (myObject == null)
throw new ArgumentNullException("myObject is null.");
_myObject = myObject;
}
It almost seems unnecessary to do this check. But I think it's because I don't completely understand what the benefits of doing this check are. It seems like a null reference exception would be thrown anyway? I am probably wrong, would really like to hear some thoughts on it.
Thank you.
To the compiler, null is a legitimate constructor argument.
Your class might be able to handle a null value for myObject. But if it can't - if your class will break when myObject is null - then checking in the constructor allows you to fail fast.
Passing a null object is perfectly legal in many cases - for this class the implementor wants to ensure that you cannot create an instance of the class w/o passing a valid Object instance though, so there have to be no checks later on - it's a good practice to ensure this as early as possible, which would be in the constructor.
if you under 4.0 you can do the following:
public ctor(IEnjection ninjaWeapon)
{
Contract.Requires<ArgumentNullException>(ninjaWeapon != null);
this.deadlyWeaponary.Add(ninjaWeapon);
}
if you under an older version, reference the Microsoft.Contract to do the same thing.
Others have already correctly stated that the passing of a null parameter may or may not be valid depending upon the functionality of the consuming code.
Where a null parameter is undesirable it is possible, from C# 7.0, to use throw expressions which allow us to rewrite null checking code much more succinctly as the following example shows:
public MyConstructor(Object myObject)
{
_myObject = myObject ?? throw new ArgumentNullException(nameof(myObject));
}
The above will set the value of _myObject to the parameter myObject unless that parameter is null, in which case an ArgumentNullException will be thrown.
The compilier has no idea about the value of an object, so you have to check this at runtime to ensure it doesn't get called with a null value.
It also depends on your particular solution. You don't need to throw the exception, I would only throw it if you can not have that value be null, and if it is null, that is an exceptional case.
I think that it is not possible to tell generally whether checking for null is necessary or not. It rather depends on whether you can live with null valued variables or not. Null is not per se a bad state. You might have situations where it is allowed for a variable to be null and other where it is not.
Ask yourself whether it makes sense to allow null values or not and design the constructor accordingly.
You could implement a simple ThrowIfNull extension method to reduce the code you write each time. Jon Skeet covered this in his blog and the referenced SO article here.
You need to explicitly check for null because the compiler doesn't know, but also because null can be a valid argument.
The benefit is that the exception will be thrown at the time of object construction, so you can easily trace which part of code is the culprit. If your code requires non-null myobject value and you don't validate it in the constructor, the NullReferenceException will be thrown when you use myObject_ and you will have to trace back manually to see who sent that null value in.

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

What exception type to use when a property cannot be null?

In my application I need to throw an exception if a property of a specific class is null or empty (in case it's a string). I'm not sure what is the best exception to use in this case. I would hate to create a new exception and I'm not sure if ArgumentNullException is appropriate in this case.
Should I create a new exception or there's an exception I can use?
I don't mind to throw an ApplicationException.
The MSDN guidelines for standard exceptions states:
Do use value for the name of the implicit value parameter of property
setters.
The following code example shows a
property that throws an exception if
the caller passes a null argument.
public IPAddress Address
{
get
{
return address;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
address = value;
}
}
Additionally, the MSDN guidelines for property design say:
Avoid throwing exceptions from
property getters.
Property getters should be simple
operations without any preconditions.
If a getter might throw an exception,
consider redesigning the property to
be a method. This recommendation does
not apply to indexers. Indexers can
throw exceptions because of invalid
arguments.
It is valid and acceptable to throw
exceptions from a property setter.
So throw ArgumentNullException in the setter on null, and ArgumentException on the empty string, and do nothing in the getter. Since the setter throws and only you have access to the backing field, it's easy to make sure it won't contain an invalid value. Having the getter throw is then pointless. This might however be a good spot to use Debug.Assert.
If you really can't provide an appropriate default, then I suppose you have three options:
Just return whatever is in the property and document this behaviour as part of the usage contract. Let the caller deal with it. You might also demand a valid value in the constructor. This might be completely inappropriate for your application though.
Replace the property by methods: A setter method that throws when passed an invalid value, and a getter method that throws InvalidOperationException when the property was never assigned a valid value.
Throw InvalidOperationException from the getter, as you could consider 'property has never been assigned' an invalid state. While you shouldn't normally throw from getters, I suppose this might be a good reason to make an exception.
If you choose options 2 or 3, you should also include a TryGet- method that returns a bool which indicates if the property has been set to a valid value, and if so returns that value in an out parameter. Otherwise you force callers to be prepared to handle an InvalidOperationException, unless they have previously set the property themselves and thus know it won't throw. Compare int.Parse versus int.TryParse.
I'd suggest using option 2 with the TryGet method. It doesn't violate any guidelines and imposes minimal requirements on the calling code.
About the other suggestions
ApplicationException is way too general. ArgumentException is a bit too general for null, but fine otherwise. MSDN docs again:
Do throw the most specific (the most derived) exception that is
appropriate. For example, if a method
receives a null (Nothing in Visual
Basic) argument, it should throw
System.ArgumentNullException instead
of its base type
System.ArgumentException.
In fact you shouldn't use ApplicationException at all (docs):
Do derive custom exceptions from the T:System.Exception class rather than the T:System.ApplicationException class.
It was originally thought that custom exceptions should derive from the ApplicationException class; however, this has not been found to add significant value. For more information, see Best Practices for Handling Exceptions.
InvalidOperationException is intended not for when the arguments to a method or property are invalid, but for when the operation as a whole is invalid (docs). It should not be thrown from the setter:
Do throw a System.InvalidOperationException exception if in an inappropriate state. System.InvalidOperationException should be thrown if a property set or a method call is not appropriate given the object's current state. For example, writing to a System.IO.FileStream that has been opened for reading should throw a System.InvalidOperationException exception.
Incidentally, InvalidOperationException is for when the operation is invalid for the object's current state. If the operation is always invalid for the entire class, you should use NotSupportedException.
I would throw an InvalidOperationException. MSDN says it "is thrown when a method call is invalid for the object's current state."
If the problem is that a member of an argument, and not the argument itself, is null then I think the best choice is the more generic ArgumentException. ArgumentNullException does not work here because the argument is in fact not null. Instead you need the more generic "something is wrong with your argument" exception type.
A detailed message for the constructor would be very appropriate here
Well, it's not an argument, if you're referencing a property of a class. So, you shouldn't use ArgumentException or ArgumentNullException.
NullReferenceException would happen if you just leave things alone, so I assume that's not what you're looking for.
So, using ApplicationExeption or InvalidOperationException would probably be your best bet, making sure to give a meaningful string to describe the error.
It is quite appropriate to throw ArgumentNullException if anyone tries to assign null.
A property should never throw on a read operation.
If it can't be null or empty, have your setter not allow null or empty values, or throw an ArgumentException if that is the case.
Also, require that the property be set in the constructor.
This way you force a valid value, rather than coming back later and saying that that you can't determine account balance as the account isn't set.
But, I would agree with bduke's response.
Does the constructor set it to a non-null value? If so I would just throw ArgumentNullException from the setter.
There is a precedent for stretching the interpretation of ArgumentNullException to meaning "string argument is null or empty": System.Windows.Clipboard.SetText will throw an ArgumentNullException in this case.
So I wouldn't see anything wrong with using this rather than the more general ArgumentException in your property setter, provided you document it.
Just throw whatever as long as the error message is helpful to a developer. This class of exception should never happen outside of development, anyway.

Throwing ArgumentNullException

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.");
}

Categories