Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func NUnit Equality Comparison

How does Equality comparison work for a Func? I have reduced the complexity of my problem to these unit tests:

[Test]
public void Will_Pass()
{
    Func<string> func = () => "key";
    Assert.That(func, Is.EqualTo(func));
}

[Test]
public void Will_Fail()
{
    Func<string> funcA = () => "key";
    Func<string> funcB = () => "key";
    Assert.That(funcA, Is.EqualTo(funcB));
}

I need to test - and successfully assert - that one instance of a Func is equal to another instance. So I basically need a way to make the Failing test pass.

Is there a way to do this without creating a custom type and overriding Equals()?

like image 605
Nick Avatar asked Jun 12 '26 11:06

Nick


1 Answers

Your failing test shouldn't pass. They're not equal functions as far as anything in .NET is concerned - at least with the current Microsoft C# compiler implementation. The delegates will refer to separate generated methods (easily verified by looking at the IL.) The language specification allows them to be equal, but doesn't require it, and I don't know of any implementation that would do this.

Equality comparison for delegates basically consists of (for a single-action delegate):

  • Do the delegates refer to the same method?
  • If the delegates have targets, are those targets equal?

The first condition will be false in your test.

like image 75
Jon Skeet Avatar answered Jun 14 '26 01:06

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!