4 01 2014
Indexed Properties
Welcome in the new year! Hope you all enjoyed your holidays 🙂
Today I will show you how to make use of indexed properties in your own classes.
Why we want it? Well, in some situations you want to give your class a partial behavoir of an array, or list, or dictionary.
Let’s use a chess board as example. As you know it’s a 8×8 matrix with A-H and 1-8.
We arrange those matrix as an two-dimensional array with 8×8 (64 fields) and get the following two classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public sealed class Board { private readonly Field[,] matrix = new Field[8, 8]; public Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { this.matrix[x, y] = new Field(); } } } } public sealed class Field { public override string ToString() { return "Hello! I'm a field!"; } } |
Next, we want to access the fields and create our first Index Property. Sure, it’s possible to create functions to get the fields, but that’s not the point 😉
Let’s keep it simple and add the following to the class “Board”. Keep in mind, that we don’t have error handling at this point!
1 2 3 4 5 6 7 |
public Field this[int x, int y] { get { return this.matrix[x, y]; } } |
Now you can access your chess board in the following way and get “Hello! I’m a field!” as output.
1 2 3 4 5 6 |
private static void Main(string[] args) { Board chessBoard = new Board(); Field chessField = chessBoard[0, 0]; Console.WriteLine(chessField); } |
You see, that we get the first field at x=0/y=0.
Now let’s create some more Indexed Properties, to make the access to the fields more comfortable, e.g. absolute index(0-63), chess position(A-H, 1-8), chess coordinates(“A1”-“H8”);
Our final “Board” class will look like the following.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
public sealed class Board { private readonly Field[,] matrix = new Field[8, 8]; public Board() { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { this.matrix[x, y] = new Field(); } } } public Field this[int x, int y] { get { return this.matrix[x, y]; } } public Field this[int index] { get { int x = index % 8; int y = index / 8; return this[x, y]; } } public Field this[char letter, int number] { get { return this[(int)letter - 'A', number - 1]; } } public Field this[string position] { get { return this[position[0], (int)position[1] - 48]; } } } |
Now you can access the fields with help of four custom indexed properties. Here is a final example for usage. Each of it will return the same field x=2;y=1
Hope, that gave you a little insight into indexed properties and their usage.
I will use this example in further posts, to show e.g. design patterns like the “Visitor Pattern”, or the “Null Pattern”.
Stay tuned!
Lets get dynamic with ExpandoObject SerializableDictionary