0

I have code which accepts a parameter on which it needs to access a Lengthproperty as well as be indexable via [index]. When I run the following code, the last line which calls the method passing an array, fails compilation with:

Cannot convert type 'int[]' to 'IArrayLike<int>'

What should my interface definition be to accept arrays as well as other classes which provide a Length property and are indexable.

interface IArrayLike<T> {
    T this[int index] { get; set; }
    int Length { get; }
}

class SomeClass<T> where T : IComparable<T> {
    public static int SomeMethod(T item, IArrayLike<T> data) {
        // code
    }
}

int[] someArray = new int[5];
SomeClass.SomeMethod(123, someArray);
4EverLive
  • 111
  • 1
  • 8
  • What are you trying to accomplish – Jawad Dec 07 '19 at 15:14
  • I am processing data which can exist in both native arrays (e.g. int[]), or "paged" arrays for large data. The paging class has multi-dimentional arrays to store large amounts of data, and it implmements Length and indexing to allow for things like binary searching, so I need to be able to call a method with either an array or an instance of a class which provides a Length property and is indexable. – 4EverLive Dec 07 '19 at 15:26

1 Answers1

0

To make it work with arrays, you should make an explicit operator. For example:

public static explicit operator ArrayLike<T>(T[] array) => new ArrayLikeImplementation<T>(array);

Make sure to also change ArrayLikeImplementation to a specific class implementation in the method implementation.

ArrayLike should be a class since it cannot be an interface too.

Source: Microsoft Documentation

misticos
  • 718
  • 5
  • 22
  • Good approach, but "new" for an interface is not going to work out. – Holger Dec 07 '19 at 15:14
  • I'm not saying it will, because this code needs to be implemented in a specific class so you'll replace new IArrayLike with the type you want in implementation. Thanks tho, I'll edit the answer. – misticos Dec 07 '19 at 15:17
  • That's what I'm getting, "user-defined conversions to or from an interface are not allowed" – 4EverLive Dec 07 '19 at 15:18
  • Because you cannot actually do this :P you'd better use a class, probably something like an abstract one. https://stackoverflow.com/questions/2433204/why-cant-i-use-interface-with-explicit-operator#2433220 – misticos Dec 07 '19 at 15:19
  • Should I then wrap an int[] into a class simply to be able to call this method? I was hoping I could somehow define an interface which will accept any native array of IComparable, or an instance of a class which implements the interface. – 4EverLive Dec 07 '19 at 15:21
  • Just create a class that inherits it? whatever – misticos Dec 07 '19 at 15:31