I would like to validate multiple parameters and throw an ArgumentNullException
if any of them are null
. For the sake of argument, let's assume I've got this:
public void DoSomething(SomeClass param1, SomeClass param2, SomeClass param3);
Of course, I could do:
if (param1 == null)
throw new ArgumentNullException(nameof(param1));
if (param2 == null)
throw new ArgumentNullException(nameof(param2));
if (param3 == null)
throw new ArgumentNullException(nameof(param3));
But it's not particularly pretty, especially if it's a recurring check in throughout the application. So, I thought I would do this:
public static class ValidationExtensions
{
public static void NullCheck<T>(this T subject)
{
if (T == null)
throw new ArgumentNullException();
}
}
// ...
param1.NullCheck();
param2.NullCheck();
param3.NullCheck();
But this way I lose the nameof
. I can't do nameof(subject)
as that's meaningless.
Of course, this is an option:
public static class ValidationExtensions
{
public static void NullCheck<T>(this T subject, string parameterName)
{
if (T == null)
throw new ArgumentNullException(parameterName);
}
}
// ...
param1.NullCheck(nameof(param1));
param2.NullCheck(nameof(param2));
param3.NullCheck(nameof(param3));
But it seems prone to error, with the repeated params... and, to be honest, just not pretty.
Is there a nice way of doing this? Ideally without using any external libraries.
param1.NullCheck(nameof(param1));
doesn't seem to be too bad - it's less error prone than your first option. What is error prone is just throwing exceptions onnull
. It's probably better to try and code without exceptions at all. Read this: Eric Lippert's Vexing Exceptions. – Jingoismparam1.NullCheck(nameof(param1));
is definitely not the end of the world, but it just feels like there should be a way to do it in a way that only refers toparam1
once... – Delirious