Home of the AlmostImplementedException

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.

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!

Now you can access your chess board in the following way and get “Hello! I’m a field!” as output.

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.

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!

Share :

, , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *