Reputation: 24378
My code is...
public static void AssertNotNull<T>(string name, T val) {
if (val == null)
throw new ArgumentNullException(String.Format("{0} must not be null", name));
}
Resharper is recommending...
public static void AssertNotNull<T>(string name, T val) {
if (Equals(val, default(T)))
throw new ArgumentNullException(String.Format("{0} must not be null", name));
}
Upvotes: 7
Views: 512
Reputation: 1562
Because it doesn't know if T
is a value type or reference type, so it makes the code work with both.
Upvotes: 14
Reputation: 4004
if you know that T will always be a class then add a where clause to say so then your origional code will be OK.
public static void AssertNotNull<T>(string name, T val)
where T : class
{
if (val == null)
throw new ArgumentNullException(String.Format("{0} must not be null", name));
}
Upvotes: 0
Reputation: 156005
This obviously isn't what you want in this instance, but it's just trying to be helpful, making sure that you don't introduce a bug by forgetting that reference types can be used for T
. Like @Michael Meadows said, you probably want to add the class
constraint to T
.
Upvotes: 2
Reputation: 16680
Those two methods are not equivalent. The first one allows AssertNotNull( "foo", 0 ) while the second throws. I think Resharper is being overzealous in this case.
Upvotes: 1
Reputation: 28426
I second Berado's answer, but would add that you can prevent this by adding the constraint below:
public static void AssertNotNull<T>(string name, T val) where T : class
Upvotes: 12