enum as array index

  • Thread starter Thread starter Gregg Teehan
  • Start date Start date
G

Gregg Teehan

Suggestions on best practive for array declare / subscript
using an enum - this is easy in Delphi / Object Pascal.

I want

private MyObjectClass [] myObjects;

myObjects = new MyObjectClass [DateTime.DayOfWeek];
myObjects [DayOfWeek.Monday] = new MyObjectClass();
myObjects [DayOfWeek.Tuesday] = new MyObjectClass();

but C# says array subscript must be int type

How best to do this.
1) what is syntax for cardinality of DayOfWeek enum?
2) what is 1st and last of enumeration?
e.g.
for (DayOfWeek index=low(DayOfWeek);
index <= high(DayOfWeek); index++)
{ . . . }

Gregg
 
Gregg,

There is nothing in the framework for this, so you will have to do it
yourself.

You can call the static GetValues method on the Enum type to get the
values in the enumeration. You can then sort that array. Once you have
that, you can get the first and last values in the enumeration.

Hope this helps.

i
 
Gregg,
In addition to Nicholas's comments.

When I want a collection keyed by an Enum, I consider using a Hashtable
instead of an Array.

This allows me to use the Enum itself for the key.

Of course the Hashtable will be more overhead then an Array (or ArrayList),
which I take into consideration.

Truthfully I normally create type safe collections with either
CollectionBase or DictionaryBase in System.Collections. In the case of an
enum index/key, I define the parameter to the indexer, as the enum.

I think when we get to .NET 2.0 (Whidbey, aka VS.NET 2004) we will have a
couple of better options available in terms of Generics! :-))

Hope this helps
Jay
 
Back
Top