Reputation: 7883
This is a best practice question.
One of our C# coding guidelines my team uses states that we use an argument guard for all arguments passed to public methods.
So, we have the guard method something like...
public void Guard (object obj, string name)
{
if (obj == null)
throw new ArgumentNullException($"{name} should not be null");
}
And then we use it like
public void MyMethod(MyObject myObject)
{
Guard (myObject, nameof(myObject)):
....
}
An internal team discussion came up the other day on whether there is any point in using this for dependency injected objects in a constructor? I would have thought perhaps not, as the DI framework would already throw an exception if the object type to be injected is not registered.
Opinion within the team was divided, and just wanted to see what the broader community opinion was.
Thanks in advance.
Upvotes: 1
Views: 267
Reputation: 4418
When you design your class, you cannot automatically assume, that it will be managed by IoC container. Somebody may take your class and use it without IoC. So considering this fact, it makes sense to protect your constructor against null input.
Moreover containers I know allow injection of custom instance, which can be even null reference. So without protection in constructor, this could be possible, but you can effectively prevent it.
Upvotes: 1