473,406 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Indexing arrays by Enums

What is the best way to index an array by an enum. Pascal has a nice feature
in that arrays can be indexed by an enum, for example

type
ButtonType = ( Left, Middle, Right ) ;

var
buttons : array[ ButtonType ] of Button ;

....
buttons[ Left ].Enabled := true ;
It appears that the only way to do this in C# is to cast the enum into an
integer, eg

enum ButtonType { Left, Middle, Right ) ;

Button[] buttons = new Button[ (int) ButtonType.Right + 1 ] ;

......
buttons[ (int) ButtonType.Left ].Enabled = true ;
Apart from the fact that the C# code is a lot less elegant and looks messy
with all the horrible casting, it's also not possible for the compiler to
check properly. Also if it becomes necessary to add another item to the enum
then you have to go through all the code and change the array declarations
and make sure that you have taken care of all the places that need changing.

In Pascal the compiler would automatically get the array declarations right
and would also flag up cases where you would need to make changes to take
care of the extra enum, eg. when walking through all items in the array.

Is there a better way of doing this in C#?

Has there been any discussion of adding arrays indexed by enums to the C#
language in the future?

Cheers

MikeS.
Nov 15 '05 #1
3 14690
"Mike Scott" <mi**@nospam.com> wrote in message
news:er**************@TK2MSFTNGP10.phx.gbl...

Mike,

[cut]
Button[] buttons = new Button[ (int) ButtonType.Right + 1 ] ; [cut] check properly. Also if it becomes necessary to add another item to the enum then you have to go through all the code and change the array declarations
and make sure that you have taken care of all the places that need

changing.

In C# you can declare an array like this:
Button[] buttons =
new Button[System.Enum.GetValues(typeof(ButtonType)).Length]
Now, if you add/remove items from the enum, size of the array
should always be ok.

HTH,
Maciej
Nov 15 '05 #2
Mike,
The way I do this is to encapsulate the downcast. I create a new class that
has an indexer with a parameter of the Enum type. I would have a private
member that contained the actual array, or a hashtable depending on if the
enum had sparse numbers or not. (sparse enum = [Flags] enum ButtonType {
Left = 1, Middle =2 , Right = 4, Top = 8, Bottom = 16 })

I would have this new class implement either ICollection or IList depending
on how flexible I wanted it. Of course inheriting DictionaryBase would
simplify the code. Inheriting CollectionBase in this regard doesn't really
make sense, as we want it indexed by the Enum, not a dynamic collection.

You can use Enum.GetValues().Length or Enum.GetNames().Length to find the
number of values in an enum, so in the constructor of the above class, you
would not need to 'hard code' the number of elements. Also a HashTable would
not be constrained by number of elements, and would support the
FlagsAttribute better.

Hope this helps
Jay

"Mike Scott" <mi**@nospam.com> wrote in message
news:er**************@TK2MSFTNGP10.phx.gbl...
What is the best way to index an array by an enum. Pascal has a nice feature in that arrays can be indexed by an enum, for example

type
ButtonType = ( Left, Middle, Right ) ;

var
buttons : array[ ButtonType ] of Button ;

...
buttons[ Left ].Enabled := true ;
It appears that the only way to do this in C# is to cast the enum into an
integer, eg

enum ButtonType { Left, Middle, Right ) ;

Button[] buttons = new Button[ (int) ButtonType.Right + 1 ] ;

.....
buttons[ (int) ButtonType.Left ].Enabled = true ;
Apart from the fact that the C# code is a lot less elegant and looks messy
with all the horrible casting, it's also not possible for the compiler to
check properly. Also if it becomes necessary to add another item to the enum then you have to go through all the code and change the array declarations
and make sure that you have taken care of all the places that need changing.
In Pascal the compiler would automatically get the array declarations right and would also flag up cases where you would need to make changes to take
care of the extra enum, eg. when walking through all items in the array.

Is there a better way of doing this in C#?

Has there been any discussion of adding arrays indexed by enums to the C#
language in the future?

Cheers

MikeS.

Nov 15 '05 #3
Hi Jay,

Unfortunately Enum.GetValues() and Enum.GetNames() are not supported on the
Compact Framework :-(

Also it's a bit of a chore to have to create a whole wrapper class just to
create a little array indexed by an enum - A one line declaration in Pascal
:-(

Cheers

MikeS.

"Jay B. Harlow [MVP - Outlook]" <Ja********@email.msn.com> wrote in message
news:e9**************@TK2MSFTNGP10.phx.gbl...
Mike,
The way I do this is to encapsulate the downcast. I create a new class that has an indexer with a parameter of the Enum type. I would have a private
member that contained the actual array, or a hashtable depending on if the
enum had sparse numbers or not. (sparse enum = [Flags] enum ButtonType {
Left = 1, Middle =2 , Right = 4, Top = 8, Bottom = 16 })

I would have this new class implement either ICollection or IList depending on how flexible I wanted it. Of course inheriting DictionaryBase would
simplify the code. Inheriting CollectionBase in this regard doesn't really
make sense, as we want it indexed by the Enum, not a dynamic collection.

You can use Enum.GetValues().Length or Enum.GetNames().Length to find the
number of values in an enum, so in the constructor of the above class, you
would not need to 'hard code' the number of elements. Also a HashTable would not be constrained by number of elements, and would support the
FlagsAttribute better.

Hope this helps
Jay

"Mike Scott" <mi**@nospam.com> wrote in message
news:er**************@TK2MSFTNGP10.phx.gbl...
What is the best way to index an array by an enum. Pascal has a nice

feature
in that arrays can be indexed by an enum, for example

type
ButtonType = ( Left, Middle, Right ) ;

var
buttons : array[ ButtonType ] of Button ;

...
buttons[ Left ].Enabled := true ;
It appears that the only way to do this in C# is to cast the enum into an integer, eg

enum ButtonType { Left, Middle, Right ) ;

Button[] buttons = new Button[ (int) ButtonType.Right + 1 ] ;

.....
buttons[ (int) ButtonType.Left ].Enabled = true ;
Apart from the fact that the C# code is a lot less elegant and looks messy with all the horrible casting, it's also not possible for the compiler to check properly. Also if it becomes necessary to add another item to the

enum
then you have to go through all the code and change the array declarations and make sure that you have taken care of all the places that need

changing.

In Pascal the compiler would automatically get the array declarations

right
and would also flag up cases where you would need to make changes to take care of the extra enum, eg. when walking through all items in the array.

Is there a better way of doing this in C#?

Has there been any discussion of adding arrays indexed by enums to the C# language in the future?

Cheers

MikeS.


Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Jens Thiede | last post by:
Quick-Fix: Can preg_match_all return the indexes of where it matched the string? More Detail: Read carefully: I'd like to seperate a string's parts into two (2) arrays which can be subdivide...
21
by: Hilde Roth | last post by:
This may have been asked before but I can't find it. If I have a rectangular list of lists, say, l = ,,], is there a handy syntax for retrieving the ith item of every sublist? I know about for i...
6
by: Michael Drumheller | last post by:
(If you're not interested in NumArray, please skip this message.) I am new to NumArray and I wonder if someone can help me with array-indexing. Here's the basic situation: Given a rank-2 array...
13
by: SpaceCowboy | last post by:
I recently got into a discussion with a co-worker about using enums across a dll interface. He wanted to use chars instead, argueing that depending on compiler settings the size of an enum could...
2
by: Faisal | last post by:
Can anyone tell me if it is possible to enumerate through all the Enums within a class . I have a class with many Enums and would like to accees the Enums through an array/collection etc. I can't...
4
by: Martin Pritchard | last post by:
Hi, I'm working on a project that historically contains around 40 enums. In the database various fields refer to the int values of these enums, but of course ref integrity is not enofrced and...
2
by: John [H2O] | last post by:
I'm having trouble slicing arrays: I thought I could do the following: Traceback (most recent call last): File "<string>", line 1, in <string> ValueError: shape mismatch: objects cannot be...
0
by: Terry Reedy | last post by:
John wrote: If these are numpy arrays, as appears, rather that array module arrays, then the numpy list might be a better place. In any case, using 'numpy' would have gotten the attention of...
0
by: Soren | last post by:
Hi, I'm trying to make a weave python extension to use in my program. I already did it in inline, but that doesn't work with py2exe (needs compiler), so I'm creating extensions instead using...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.