W
Whitney Kew
I have a class, MyObject, that implements IEquatable<MyObject>. I'm
trying to get the intersection of two MyObject[] arrays. According to
the documentation for IEnumerable<T>.Intersect(), it's supposed to use
the default equality comparer, EqualityComparer<T>.Default, to compare
values. That, in turn, according to the docs, checks whether type T
implements the System.IEquatable<T> generic interface, and if so
returns an EqualityComparer<T> that uses that implementation.
However, the Intersect() method doesn't seem to be calling
MyObject.Equals(). Here is my source code; the output, I thought,
should return the object represented by MyObject(2). The result I'm
getting is an empty collection. Am I missing something?
using System;
using System.Linq;
namespace Test
{
class MyObject : IEquatable<MyObject>
{
public int Number { get; private set; }
public MyObject(int number)
{
Number = number;
}
public bool Equals(MyObject other)
{
return Number.Equals(other.Number);
}
// ...ToString() for Console.WriteLine()...
}
class Program
{
static void Main(string[] args)
{
MyObject[] objects1 = { new MyObject(1), new MyObject(2) };
MyObject[] objects2 = { new MyObject(2), new MyObject(3) };
foreach (MyObject obj in objects1.Intersect(objects2))
Console.WriteLine(obj);
}
}
}
trying to get the intersection of two MyObject[] arrays. According to
the documentation for IEnumerable<T>.Intersect(), it's supposed to use
the default equality comparer, EqualityComparer<T>.Default, to compare
values. That, in turn, according to the docs, checks whether type T
implements the System.IEquatable<T> generic interface, and if so
returns an EqualityComparer<T> that uses that implementation.
However, the Intersect() method doesn't seem to be calling
MyObject.Equals(). Here is my source code; the output, I thought,
should return the object represented by MyObject(2). The result I'm
getting is an empty collection. Am I missing something?
using System;
using System.Linq;
namespace Test
{
class MyObject : IEquatable<MyObject>
{
public int Number { get; private set; }
public MyObject(int number)
{
Number = number;
}
public bool Equals(MyObject other)
{
return Number.Equals(other.Number);
}
// ...ToString() for Console.WriteLine()...
}
class Program
{
static void Main(string[] args)
{
MyObject[] objects1 = { new MyObject(1), new MyObject(2) };
MyObject[] objects2 = { new MyObject(2), new MyObject(3) };
foreach (MyObject obj in objects1.Intersect(objects2))
Console.WriteLine(obj);
}
}
}