JeremyWeir
JeremyWeir

Reputation: 24378

Why is resharper making the following recommendation?

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

Answers (6)

Beardo
Beardo

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

Damien McGivern
Damien McGivern

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

Tundey
Tundey

Reputation: 2965

I suppose because T could be a non-reference type.

Upvotes: 0

bdukes
bdukes

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

Greg
Greg

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

Michael Meadows
Michael Meadows

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

Related Questions