Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic list class in c#

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 ?

like image 745
Jacco Avatar asked Feb 19 '13 16:02

Jacco


People also ask

What are generic classes?

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.

What is a generic linked list?

Implementation of linked lists that may store any data type is known as a generic linked list. Integers are stored in one linked list, while floats are stored in the other.

What are generic functions in C?

A generic function is a function that is declared with type parameters. When called, actual types are used instead of the type parameters.


2 Answers

It's called an indexer, written like so:

public T this[int i]
{
    get
    {
        return array[i];
    }
    set
    {
        array[i] = value;
    }
}
like image 198
Rich O'Kelly Avatar answered Sep 23 '22 02:09

Rich O'Kelly


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; }
  }
like image 41
developer747 Avatar answered Sep 26 '22 02:09

developer747