0

I'm trying to make a class where you can access a collection in it and get an item using a string index, (I hope this makes sense), basically I would like to know either what this is called or how to do it?

here is an example of what I mean;

string blah = SomeClass.Items["Item1"].ToString();

Hopefully someone can make some sense of this.

Thank You.

Tom O
  • 1,780
  • 2
  • 20
  • 43
  • I guess it makes sense but how do you determine what the string name is? You can make your indexers do and return anything you want. – Jeff Mercado May 20 '12 at 18:34
  • It's probably a `Dictionary`. Or you can implement your own collection. The indexer (the square brackets) is implemented as the 'this' property. See http://stackoverflow.com/questions/287928/how-do-i-overload-the-square-bracket-operator-in-c – Roger Lipscombe May 20 '12 at 18:35

5 Answers5

2

I think you are looking for an indexer.

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

In your case you want to index using a string. Something like this:

public MyItem this[string index]
{
    get { return ... }
}

It may be that you would be better off removing the Items layer from your syntax. That would result in your code reading like this:

string blah = SomeClass["Item1"].ToString();
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

You mean a string indexer.

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

Use a Dictionary<string, string>.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
0

You can use a wrapper around a List to get the "Items" property.

public class MyClass
{

  private readonly List<string> _myColl = new List<string>();

  public List<string> Items
  { 
    get { return this._myColl; }
  }

}

You can then use it like so:

MyClass c = new MyClass();
c.Items.Add("something");

If you need a string key, you can always switch List to Dictionary<string, string>

public class MyClass
{

  private readonly Dictionary<string, string> _myColl = new Dictionary<string, string>();

  public Dictionary<string, string> Items
  { 
    get { return this._myColl; }
  }

}

Then use it like so:

MyClass c = new MyClass();
c.Items.Add("somekey", "somevalue");

I guess the point is that you can wrap just about any collection with this pattern to fit almost any need.

Chris Gessler
  • 22,727
  • 7
  • 57
  • 83
0

As people have said, an indexed property is one option. Tutorial here

http://msdn.microsoft.com/en-us/library/aa288464(v=vs.71).aspx

Charleh
  • 13,749
  • 3
  • 37
  • 57