generic list class in c#
Asked Answered
E

2

5

I'm currently making my own very basic generic list class (to get a better understanding on how the predefined ones work). Only problem I have is that I can't reach the elements inside the array as you normally do in say using "System.Collections.Generic.List".

GenericList<type> list = new GenericList<type>();
list.Add(whatever);

This works fine, but when trying to access "whatever" I want to be able to write :

list[0];

But that obviously doesn't work since I'm clearly missing something in the code, what is it I need to add to my otherwise fully working generic class ?

Euchologion answered 19/2, 2013 at 16:24 Comment(2)
What does your GenericList class look like?Supercilious
Incidentally, one feature which can be useful in a generic list is a method like public void ActOnElement<TP1>(int index, ActByRef<T,TP1> proc, ref TP1 param1) { proc(ref Array[index], ref TP param1); } which will allow code to act directly on a list item [assume public delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2);]. If one has e.g. a GenericList<Rectangle>, such a method can allow code to say myList.ActOnItem(index, (ref Rectangle r, ref int v) => {r.X -= v; r.Width+=v;}, ref widthAdjust) to update a list item "in-place".Burweed
M
12

It's called an indexer, written like so:

public T this[int i]
{
    get
    {
        return array[i];
    }
    set
    {
        array[i] = value;
    }
}
Mosier answered 19/2, 2013 at 16:25 Comment(3)
I suspect that the OP may mean he is getting Only assignment, call, increment, decrement and new object expressions can be used as a statement when accessing the instance of GenericList? Obviously if he can't even access the index then your answer is fine :)Supercilious
@Supercilious I believe the OP was looking for the property declaration to put within their GenericList type such that: given an instance of GenericList list, they can access an element within it using an indexer eg list[0].Tamtama
I suspected as much, was just thinking of how the OP could be mis-interpreted. Anyway, +1 :)Supercilious
S
1

I think all you need to do is implement IList<T> , to get all the basic functionality

  public interface IList<T>  
  {

    int IndexOf(T item);

    void Insert(int index, T item);

    void RemoveAt(int index);

    T this[int index] { get; set; }
  }
Seascape answered 19/2, 2013 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.