Update for C# 7
You can use a throw expression with the null coalescing operator. Here is an example from that page:
public string Name
{
get => name;
set => name = value ??
throw new ArgumentNullException(paramName: nameof(value), message: "New name must not be null");
}
Original Answer
Personally, I use the ThrowIfNull
extension method. I don't know who to credit but I definitely didn't invent it. It's nice because you can do assignment with the return value:
public static T ThrowIfNull<T>(this T argument, string argumentName)
{
if (argument == null)
{
throw new ArgumentNullException(argumentName);
}
return argument;
}
Usage:
this.something = theArgument.ThrowIfNull("theArgument");
// or in C# 6
this.something = theArgument.ThrowIfNull(nameof(theArgument));
(Although some people think it's weird to call an extension method on a null instance)
If you really want to check more than one argument at a time, your example might be more streamlined if you used a params
signature like so:
public static void CheckAndThrowArgNullEx(params object[] argsAndNames)
{
for (int i = 0; i < argsAndNames.Length; i += 2)
{
if (argsAndNames[i] == null)
{
string argName = (string)argsAndNames[i + 1];
throw new ArgumentNullException(argName);
}
}
}
and the usage would be:
CheckAndThrowArgNullEx(arg1, "arg1", arg2, "arg2");
// or in C# 6
CheckAndThrowArgNullEx(arg1, nameof(arg1), arg2, nameof(arg2));
On second thought, as KeithS mentions in the comments, it would probably be better to implement this as a set of overloads rather than using params object[]
like this:
static void Check(object arg1, string arg1Name) { ... }
static void Check(object arg1, string arg1Name, object arg2, string arg2Name) { ... }
// and so on...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…