Any idea why the func is returning false? Equals does not fire as well!!!
class Program
{
static void Main(string[] args)
{
Func<Person, SomethingElse, bool> matchNested =
(p, s) => p.Nested == s.Nested;
var matched = matchNested(new Person()
{
Age = 10,
Nested = new Nested()
{
Validity = DateTime.Today
}
},
new SomethingElse()
{
Age = 10,
Nested = new Nested()
{
Validity = DateTime.Today
}
});
Console.WriteLine(matched);
}
}
internal class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Nested Nested { get; set; }
}
internal class SomethingElse
{
public string Name { get; set; }
public int Age { get; set; }
public Nested Nested { get; set; }
}
internal class Nested
{
public DateTime Validity { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
if (!this.Validity.Equals((obj as Nested).Validity))
return false;
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
I’m not going to bother trying to figure out what your
Equalscode is trying to do, I’m just saying why it isn’t being called and why you are always getting false.By default the
==operator returns true for reference types where they point at the same object, according to the docs.So what you could do is overload the operator in your
Nestedclass, or callp.Nested.Equals(s.Nested). If you go the overload route, you will need to overload!=also.If you go the
Equalsroute, you can have yourNestedclass implement theEquatable<T>interface so you get a strongly-typedEqualsmethod instead of one takingobject.