Reflection is kind of like black magic, and whenever I use it I feel like some kind of wizard. The ability to look into objects and even invoke private methods is pretty darn powerful. It’s not all that magical, of course, since it is built into the framework… however, you should still be careful because it is fairly slow. If you need to do a lot of reflection, it would probably be beneficial to think about how to speed things up, if possible.
I came across a scenario where I was defining a bunch of string constants in a class (something you might do if you were trying to avoid magic strings), and I wanted to pull all of those constants into an array.
One quick LINQ statement is all we need to pull the information into an array. Consts are Fields because they don’t have getters/setters, and we do some additional checks to make sure we’re getting consts of the specified type. You could easily change this around to get other constant types by removing the string type checking.
Note that I’m using a lazy-loading technique because I only want to do the heavy reflection lifting once.