Checking for 'null'
-
07-03-2021 - |
Question
Does C#
has some rule of thumb or a coding convention contract, which handles the possible null
argument?
As an example, I'm writing a custom method, which retrieves a byte[] data
parameter.
public static string ConvertDataToMyOwnAndCustomString(byte[] data) { ... }
Now - what should I do if the passed data
is null
?
Should I leave it as it is so that a possible NullReferenceException
occurs? Or should I write a check and do something like this:
if (data == null) return null;
Solution
The generally accepted pattern is to throw an ArgumentNullException
if(data == null) { throw new ArgumentNullException("data"); }
if it is indeed an error for clients to be passing null
to your method. These days, you can even enforce the requirement through a Code Contract:
Contract.Requires(data != null);
Of course, it might very well be the case that null
is not an error for your method. That's for you to decide though, not us. But don't return null
to indicate to your client that an error occurred.
OTHER TIPS
I think the most common pattern is:
if(data == null)
throw new ArgumentNullException("data");
It really all depends. Where does this method live? How often will it be reused? Is it only for this application, or is it part of a code library that will be utilized again?
If it is going to be used, especially by other applications/developers then I would still test for data being null
, but then I would throw an exception. You don't want it to choke silently.
If this is a one-off method that is for code that will surely never be reused or revisited, you could just test for null
and return null
. Remember, though, this is only appropriate because you know of the outcome. If there is any chance some other application will use this, or another developer, I'd test for null
then throw an exception (most likely an ArgumentNullException
).
Jason and Christopher's answers are correct. I just want to add to them;
If it is likely and not an exceptional condition that you could get null
for that parameter, you should not throw an exception, but instead return an appropriate value - very often, null
itself works.
For example, with some systems of model binding, a missing text value might result in a null
being passed as a parameter. Such an occurrence might be an error, but not an 'exceptional' one.