How can I inherit from ArrayList <MyClass>?

I want to inherit from some class array / vector / list so that I can add only one additional specialized method to it ... something like this:

public class SpacesArray : ArrayList<Space> { public Space this[Color c, int i] { get { return this[c == Color.White ? i : this.Count - i - 1]; } set { this[c == Color.White ? i : this.Count - i - 1] = value; } } } 

But the compiler will not allow me. He speaks

The non-generic type 'System.Collections.ArrayList' cannot be used with type arguments

How can i solve this?

+6
collections inheritance c #
source share
3 answers

ArrayList not shared. Use List<Space> from System.Collections.Generic.

+11
source share

No ArrayList<T> . List<T> works pretty well.

 public class SpacesArray : List<Space> { public Space this[Color c, int i] { get { return this[c == Color.White ? i : this.Count - i - 1]; } set { this[c == Color.White ? i : this.Count - i - 1] = value; } } } 
+2
source share

You can create a wrapper around ArrayList<T> that implements IReadOnlyList<T> . Something like:

 public class FooImmutableArray<T> : IReadOnlyList<T> { private readonly T[] Structure; public static FooImmutableArray<T> Create(params T[] elements) { return new FooImmutableArray<T>(elements); } public static FooImmutableArray<T> Create(IEnumerable<T> elements) { return new FooImmutableArray<T>(elements); } public FooImmutableArray() { this.Structure = new T[0]; } private FooImmutableArray(params T[] elements) { this.Structure = elements.ToArray(); } private FooImmutableArray(IEnumerable<T> elements) { this.Structure = elements.ToArray(); } public T this[int index] { get { return this.Structure[index]; } } public IEnumerator<T> GetEnumerator() { return this.Structure.AsEnumerable().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return this.Structure.Length; } } public int Length { get { return this.Structure.Length; } } } 
+2
source share

All Articles