StephenCleary / Comparers

The last comparison library you'll ever need!
MIT License
427 stars 33 forks source link

EquatableBaseWithOperators: System.NullReferenceException : Object reference not set to an instance of an object. #11

Closed yinyue200 closed 6 years ago

yinyue200 commented 6 years ago
    class Test:Nito.Comparers.EquatableBaseWithOperators<Test>
    {
        static Test()
        {
            DefaultComparer = Nito.Comparers.EqualityComparerBuilder.For<Test>().Default();
        }
    }
        [Fact]
        public void Test1()
        {
            Test a = null;
            Assert.True(a == null);
        }

this code failed with

   System.NullReferenceException : Object reference not set to an instance of an object.
   Stack Trace:
        at Nito.Comparers.Util.ComparableImplementations.ImplementOpEquality[T](IEqualityComparer`1 equalityComparer, T left, T right)
StephenCleary commented 6 years ago

In this code, the static Test constructor is never called, so Test.DefaultComparer is null.

You have to force the Test constructor to be called, e.g., by creating a Test instance:

[Fact]
public void Test1()
{
  var _ = new Test();
  Test a = null;
  Assert.True(a == null);
}