M
Mike Scott
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.
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.