Sunday, April 4, 2010

C# - Enumerator Indexed Arrays

Anders Hejlsberg unfortunately forgot to include a very neat feature from his previous masterpiece with C#. I sorely miss my Enumerator Indexed Arrays ;-(. I used to write code that would look like this in C#;

Enum ChessPieces  {queen, rook, bishop, king, pawn, knight};
int[] pieceValue = new int[ChessPieces];
-- A loop using this
foreach (Piece in ChessPieces) {totalValue += PieceValue[Piece];}
-- A lookup
var value = pieceValue[queen];

This code is safe, clear and concise. But does not work in C#. There are several ways to do things along these lines in C#. All of them use more code, casting and/or ugly constructs. There is only one realistic option; support for it in the language itself!

No comments:

Post a Comment