1

This might be a very basic question, but really don't know how to make it. I want to create the following:

public class MyArray
{
    List<KeyValuePair<int, object>> myList = new List<KeyValuePair<int, object>>();

    public void Set_Value(int index, object value)
    {
        myList = myList.Where(a => a.Key != index).ToList();
        myList.Add(new KeyValuePair<int, object>(index, value));
    }
    public object Get_Value(int index)
    {
        if (myList.Any(a => a.Key == index)) return myList.FirstOrDefault(a => a.Key == index).Value;
        else return null;
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyArray array = new MyArray();
        array[0] = "Hello world!";
    }
}

Make a array that i manipulate myself...

ikwillem
  • 1,006
  • 1
  • 10
  • 23

2 Answers2

1

You can add an index operator to your class:

public object this[int index]
{
    get
    {
        if (myList.Any(a => a.Key == index)) return myList.FirstOrDefault(a => a.Key == index).Value;
        else return null;
    }
    set
    {
        myList = myList.Where(a => a.Key != index).ToList();
        myList.Add(new KeyValuePair<int, object>(index, value));
    }
}

Note that you have several opportunities to improve your code; I just copy/pasted it to show the mechanics of the index operator.

D Stanley
  • 144,385
  • 11
  • 166
  • 231
0

I think what you're asking is how you overload the indexer operator.

For that, see here: How do I overload the [] operator in C#

However, I'd advise against recreating the wheel here. It's probably better to actually use an array or inherit from a collection class.

Community
  • 1
  • 1
Colin
  • 3,915
  • 19
  • 39
  • If you feel that a question is answered by another question you should flag/vote to close it as a duplicate, not post an answer with a link to the duplicate question. – Servy May 07 '15 at 17:21