Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NUnit's Assert.That(..) have ref overloads?

Tags:

c#

nunit

Maybe I'm just being dumb but when and why would you use:

NUnit.Framework.Assert.That<T>(ref T, NUnit.Framework.Constraints.IResolveConstraint, string, params object[])
NUnit.Framework.Assert.That<T>(ref T, NUnit.Framework.Constraints.IResolveConstraint, string)
NUnit.Framework.Assert.That<T>(ref T, NUnit.Framework.Constraints.IResolveConstraint)

in place of:

NUnit.Framework.Assert.That(object, NUnit.Framework.Constraints.IResolveConstraint, string, params object[])
NUnit.Framework.Assert.That(object, NUnit.Framework.Constraints.IResolveConstraint, string)
NUnit.Framework.Assert.That(object, NUnit.Framework.Constraints.IResolveConstraint)

What advantage does passing by ref bring to this these methods?

like image 729
chillitom Avatar asked Feb 11 '11 10:02

chillitom


1 Answers

Digging into NUnit source code, I found this:

static public void That<T>(ref T actual, IResolveConstraint expression, string message, params object[] args)
{
    Constraint constraint = expression.Resolve();

    Assert.IncrementAssertCount();
    if (!constraint.Matches(ref actual))
    {
        MessageWriter writer = new TextMessageWriter(message, args);
        constraint.WriteMessageTo(writer);
        throw new AssertionException(writer.ToString());
    }
}

    public virtual bool Matches<T>(ref T actual)
    {
        return Matches(actual);
    }

versus:

    static public void That(object actual, IResolveConstraint expression, string message, params object[] args)
    {
        Constraint constraint = expression.Resolve();

        Assert.IncrementAssertCount();
        if (!constraint.Matches(actual))
        {
            MessageWriter writer = new TextMessageWriter(message, args);
            constraint.WriteMessageTo(writer);
            throw new AssertionException(writer.ToString());
        }
    }

As you can see, there is no difference in the implementation. The Ref T actual overload allows you to pass value types as reference as well, while reference types are already passed as reference.

like image 184
Edwin de Koning Avatar answered Sep 18 '22 12:09

Edwin de Koning