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);
2
  • What are you trying to accomplish Commented Dec 7, 2019 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. Commented Dec 7, 2019 at 15:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Good approach, but "new" for an interface is not going to work out.
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.
That's what I'm getting, "user-defined conversions to or from an interface are not allowed"
Because you cannot actually do this :P you'd better use a class, probably something like an abstract one. stackoverflow.com/questions/2433204/…
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.