0

I'm trying to implement a class with a generic type T, which in practice could be either scalar variables (int, float, etc.) or arrays of scalar variables (int[], float[], etc.).

In one of that class's methods, I'd like to do equality comparisons using that type. If it's a scalar, I want them compared directly. And if it's an array, I want to compare structural equality (i.e. all elements of the array have the same value in the same order). Is this possible? I'm really struggling with finding a common interface to constrain the generic type that would encompass both scalars and arrays of scalars to allow me to do this comparison.

public class Foo<T>
{
    public Foo() {}
    public bool DoComparison(T x, T y)
    {
        // This is the comparison I'm trying to figure out how to implement
        // If scalars, returns true if x == y, otherwise false
        // If arrays, returns true if x is structurally equal to y, otherwise false
        if(x.IsEqualToOrStructurallyEqualTo(y)) 
        {
            return true;
        }
        else
        {
            return false;
        }

    }
}
  • Can't you treat the scalar version as array with length 1? – Stefan Mar 25 '21 at 18:59
  • `typeof(T).IsArray`. And then there's that question of do you want to test whether they are the same array, or contain all the same values, but you can deal with that once you've gone down the `IsArray` code path. – jwdonahue Mar 25 '21 at 19:05
  • BTW: It is not clear what is meant by "structurally equal to". – jwdonahue Mar 25 '21 at 19:07
  • Also, `x.Equals(y)` is what you'd normally do, and leave it up the T type to define exactly what equality means. – jwdonahue Mar 25 '21 at 19:10

0 Answers0