Checking for Null in Constructor - c#

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.

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

What is the proper way to check for and handle null return values?

I have some methods that return a value (or object) if all went as planned, otherwise return null (something went wrong).
For example, DataTable dt = DoSomething(); If something blew up in DoSomething() the return value would be null and dt would be set to null.
There are other cases where I'm testing for a value and then setting a variable to the value if the test value is not null. This doesn't feel right. I'm calling the same method twice.
For example, if (String.IsNullOrEmpty(getAddresss())) {Do Stuff;} If I declare a variable before the test, the code could blow up when it gets set. If I test, then set it seems like I'm duplicating work.
What is the preferred way to test for and handle null values?
Throw exceptions from your methods instead of having them return null.
Regardless of where you stand in the almost religious arguments between return codes and exceptions, it's a fact that .NET is built on the premise of reporting errors by throwing exceptions. It would be really ill advised to follow a practice so detached from the rest of the framework for your code, if nothing else because of the unfamiliarity this will pose to others.
Is the duplication of work that important? It's all a null-check, after all (read: premature optimization).
I don't believe there's a shorter way, so just do the checks.
Another way to do this is to throw an exception in DoSomething(). That way, the actual reason for something blowing up can be logged, handled, passed on, etc.
Usually the coalesce operator (??) is pretty useful:
String myMessage = returnedValue ?? "Unspecified";
If the value being tested (returnedValue in this case) is not null, then it's returned; otherwise, the value on the right hand side of the operator is returned.
Here's the C# specification on the operator.
Everything depend of the reason why the null is returned.
What you can do is:
Use Null pattern
throw an own Exception
Code Contracts can help you in handling null values. Here's a short introduction http://devjourney.com/blog/code-contracts-part-1-introduction/

check against: null vs default()?

I want to check if a reference type is null. I see two options (_settings is of reference type FooType):
if (_settings == default(FooType)) { ... }
and
if (_settings == null) { ... }
How do these two perform differently?
There's no difference. The default value of any reference type is null.
MSDN's C# reference page for default keyword: https://msdn.microsoft.com/en-us/library/25tdedf5.aspx.
Now that we don't need to pass the type to default anymore, default is preferred.
It is just as readable
It can be used both for value and reference types
It can be used in generics
if (_settings == default) { ... }
Also, after calling
obj = enumerable.FirstOrDefault();
it makes more sense to test for default after that and not for null. Otherwise it should have been FirstOrNull, but value dont have a null value but do have a default.
There is no difference, but second one is more readable. The best place to use default is when you deal with generics. Common code is return default(T);
Not different but I think
if (_settings == null) { ... }
is clearer.
My understanding is they are not different. It only matters when you are dealing with value types.
I would definitely go with the specific check against null. Because if the type of the _settings class ever changes you may run into reference issues. At minimum it would require a change to the code breaking the open/close policy.
if( _settings == null ) {...}
This IMO is safer and cleaner.
As has been mentioned, there is no difference... but you might want to use default(<type>) anyway, to handle the cases where it's not a reference type. Typically this is only in generics, but it's a good habit to form for the general case.

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 throw for strings

If I've got the following, really for any string where you check IsNullOrEmpty and it turns up empty, what kind of exception type should one throw, and it's not a argument to a method?
I always have a hard time picking exception types because there are so damn many of them. And this is just grabbing a value from the web.config and checking if SandboxSoapApiUsername returned empty.
if(string.IsNullOrEmpty(ConfigUtility.SandboxSoapApiUsername))
throw new WTF do I throw here??? ahhh
It probably depends on the use/context right? Well I will use the string returned to set a class private field. So I need to check if it's empty string early in the process rather than later (rather than rely on other code to check the property related to the private field I will set ConfigUtility.SandboxSoapApiUsername to).
Since the properties in this class that I'm setting each ConfigUtility.MEthodName to is going to be used in a SOAP request I thought maybe UriFormatException would be appropriate here even though this is not the Uri?
Methods in the .NET Framework usually distinguish between null and an invalid value passed in for an argument. I think you should throw an Argument​Null​Exception if the value is null and an Argument​Exception if it's invalid.
if (arg == null)
throw new ArgumentNullException("arg", "argcannot be null");
if (arg == string.Empty)
throw new ArgumentException("arg cannot be an empty string", "arg");
If the value is not an argument, but, for example, loaded during initialization, I think a Invalid​Operation​Exception would be appropriate:
if (string.IsNullOrEmpty(ConfigUtility.SandboxSoapApiUsername))
throw new InvalidOperationException("Cannot initialize because " +
"SandboxSoapApiUsername not configured");
It depends when the string comes from. An argument might cause an ArgumentNullException. Configuration might throw a ConfigurationException (which seems to be applicable to this case). Or you can of course create your own anyway.
You will really spend most of your time picking from of the list below when throwing a new exception (as opposed to simply doing a throw).
ConfigurationException
The exception that is thrown when a configuration system error has occurred.
ArgumentException
The exception that is thrown when one of the arguments provided to a method is not valid.
InvalidOperationException
The exception that is thrown when a method call is invalid for the object's current state.
1)
This arguably doesn't make sense unless you're picking the setting from an app.config or web.config:
The ConfigurationException exception
is thrown if the application attempts
to read or write data to the
configuration file but is
unsuccessful. Some possible reasons
for this can include malformed XML in
the configuration file, file
permission issues, and configuration
properties with values that are not
valid.
2)
It's not an argument so this one doesn't make much sense.
3)
This is the best of the three as the object will be in an invalid state. However depending on how big your set of configuration settings is, I would prefer to make my own Exception derived from System.Exception.
There's two schools of thought about which to derive from - System.Exception and ApplicationException*. Two different developers on the framework team have expressed different views on which they think you should inherit from, I stick with Jeffrey Richter's view.
If all the above sounds like woffle, then you could just pick one you think is most relevant from the list.
*Looks like MSDN now agrees with its framework devs that ApplicationException was a design mistake
you need an InvalidConfiguration exception - define one
throw new InvalidConfigurationException("Must supply user name")
If its passed as an argument, throw ArgumentNullException.
Otherwise, it really depends on what the string being null means in the context of your application. Don't be afraid to define custom Exception types if there isn't something in the base framework for the scenario.
Since it seems something wasn't configured correctly, I'd suggest System.Configuration.ConfigurationErrorsException.
Note: don't use System.Configuration.ConfigurationException. It's an older version and has been deprecated.
Note 2: Though I'm 90% sure we're dealing with a missing configuration value, if it's an method parameter that's missing, throw an ArgumentException or ArgumentOutOfRangeException.

Categories