Why is ThrowIfNull implemented as:
static void ThrowIfNull<T>(this T argument, string name) where T : class
{
if (argument == null)
{
throw new ArgumentNullException(name);
}
}
Wouldn’t it be better rewritten as:
static void ThrowIfNull<T>(this T argument, string name) where T : class
{
if (object.ReferenceEquals(argument, null))
{
throw new ArgumentNullException(name);
}
}
Pros: it helps avoiding confusing Equals overloads and probably makes the code more clear.
Any cons to that? There should be some.
There’s no difference between the two. You’re confusing overriding
Equals(which isn’t called in either implementation) with overloading==(which won’t be relevant in either snippet as overloading is performed at compile time, and the compiler doesn’t know enough aboutTto use any specific overload).Just to show what I mean:
Testing with:
ThrowIfFoodoesn’t know thatTwill be a string – because that depends on the calling code – and the overload resolution is only performed whenThrowIfFoois compiled. Therefore it’s using the operator==(object, object)rather than==(string, string).In other words, it’s like this:
In the last line, the compiler knows it can use the overload of == because both operands have compile-time types of
string.