C#: public method{get{} set{}} question

Nyight picture Nyight · Sep 24, 2009 · Viewed 7.8k times · Source

I'm not entirely sure if I have all the terminology correct so forgive me if I'm wrong. I was wondering if it would be possible to send an argument(s) to the method. Take the following for example.

public item (int index)  
{  
    get { return list[index]; }  
    set { list[index] = value; }  
}

I know that as it is, it will error. What I'm asking is if there is some way to get it working. Any suggestions or should I figure out some way around it?

Thanks in advance.

Answer

Andrew Hare picture Andrew Hare · Sep 24, 2009

Try this:

// This returns an instance of type "Foo",
// since I didn't know the type of "list".
// Obviously the return type would need to
// match the type of whatever "list" contains.
public Foo this[int index]
{
    get { return list[index]; }
    set { list[index] = value; }
}

This is C#'s indexer syntax and it has some limitations (it's not as flexible as VB.NET's parameterful properties) but it does work for your specific example.