I’m doing some work with stats, and want to refactor the following method :
public static blah(float[] array)
{
//Do something over array, sum it for example.
}
However, instead of using float[] I’d like to be using some kind of indexed enumerable (to use dynamic loading from disk for very large arrays for example).
I had created a simple interface, and wanted to use it.
public interface IArray<T> : IEnumerable<T>
{
T this[int j] { get; set; }
int Length { get; }
}
My problem is :
- float[] only inherits IList, not IArray, and AFAIK there’s no way to change that.
- I’d like to ditch IArray and only use IList, but my classes would need to implement many methods like
Add,RemoveAtalthough they are fixed size - And then my question : how can float[] implement IList whereas it doesn’t have these methods ?
Any help is welcome.
Cheers
Array of T also implements
IList<T>and others (but these don’t always show in tools, several aspects of Array as special cased by the runtime).This is true, but such implementation is quite quick to do (and should you only need non-modifying operations, you can just throw a
NotImplementedExceptionfrom modifying methods).In practice in only takes a few minutes to do, and your implementation should be reusable. Also there are types like
ReadOnlyCollection<T>to help avoid a lot of this work.A type can explicitly implement interface methods. They are not directly members of the type, but casting to the interface (or reflection) will allow access. This allows a typed collection to implement
IEnumerator.Current(returningObject) while also providing aCurrentproperty that returns the correct type.