Colonel Panic
Colonel Panic

Reputation: 137742

Is there a functional difference between Assert.IsNotNull(·) Assert.AreNotEqual(null,·)?

Is there a functional difference between Assert.IsNotNull(·) Assert.AreNotEqual(null,·)?

I prefer the first, as it's more readable. A colleague used the second, I wondered if there's also a functional difference. I know comparing objects to null can sometimes be weird (the difference between .Equals and ==).

Upvotes: 2

Views: 4922

Answers (2)

Magnus Grindal Bakken
Magnus Grindal Bakken

Reputation: 2113

The short answer is no.

The long answer involves looking at the actual source code. I retrieved this using a decompiler, so some of it may look a little weird. The comments are added by me.

// The IsNotNull overload that takes only "value" calls this one internally
public static void IsNotNull(object value, string message, params object[] parameters)
{
  if (value != null)
    return;
  Assert.HandleFail("Assert.IsNotNull", message, parameters);
}

// The AreNotEqual that takes only "notExpected" and "actual" calls this one internally
public static void AreNotEqual<T>(T notExpected, T actual, string message, params object[] parameters)
{
  if (!object.Equals((object) notExpected, (object) actual))
    return;
  Assert.HandleFail("Assert.AreNotEqual", (string) FrameworkMessages.AreNotEqualFailMsg(message == null ? (object) string.Empty : (object) Assert.ReplaceNulls((object) message), (object) Assert.ReplaceNulls((object) notExpected), (object) Assert.ReplaceNulls((object) actual)), parameters);
}

It's true that there's a difference between comparing with == and Equals, but it shouldn't make a difference when you're comparing to null. As you can see, AreNotEqual casts the input values to object and uses the standard static Equals implementation on the object class, which is implemented as follows:

public static bool Equals(Object objA, Object objB) 
{
    if (objA==objB) {
        return true;
    } 
    if (objA==null || objB==null) {
        return false; 
    } 
    return objA.Equals(objB);
}

In my opinion, IsNotNull is clearer than AreNotEqual, and the error message if gives when the assert fails is probably easier to understand at a glance.

Upvotes: 2

Odrai
Odrai

Reputation: 2353

IsNotNull: Verifies that the specified object is not null. The assertion fails if it is null.

AreNotEqual: Verifies that two specified objects are not equal. The assertion fails if the objects are equal.

So the function IsNotNull only verifies that one specified object is not null, while AreNotEqual compares two objects. The IsNotNull function will be a (little) bit faster.

Upvotes: 1

Related Questions