I'm reading and learning about reflection in C#. It would be fine to know how can it help me in my daily work, so I want people with more experience than me tell me samples or ideas about what kinds of things can we achieve using it, or how can we reduce de amount of code that we write.
Thanks.
The properties window in VS is reflection based - if you make a user control you can modify any properties on it from the
PropertyGrid
(its also a control you can use if you want) instantly. Of course you can add attributes to enhance how it is displayed (which are accessed via reflection).I've also used it to implement a custom binary serialization class.
Here I have a class where I use reflection to serialize / de-serialize it - and provide attributes for additional UI information.
#region Properties (5)
And serialization function - as you can see, it just takes an object and the byte order (endianness) you want. Everything else is determined by reflection. The default
SerializationProvider
works usingSerializedPosition
attributes on fields within the object (private or not).Reflections are nice for "late binding" solutions where you do not want to have a physical reference connected to your project but rather "connect" it later on. That way if the reference is not there and it is not critical, you get no unhandlish errors of missing references. You get a controlled error that you can handle.
I've only used reflection in production code once. It was a situation where I had to make adjustments to what - up to that point in time - had been standardised usage of a particular class method in a startup routine (sorry not to be more specfic - it was a while ago and the details are hazy). The only way round the problem was to introduce a different version of the method and examine various criteria/code conditions etc. at runtime to determine which method I should be calling. It was a pretty compact piece of code that provided a succint solution to what would otherwise have been a messy problem to solve.
I use it for:
It is invaluable for library code that doesn't have any need to know about the caller - like with generics, but richer access to the data. Examples:
You should of course try to minimise the amount of reflection you do, but you can mitigate the cost by caching delegates from
Delegate.CreateDelegate
/Expression
/DynamicMethod
This is way to execute methods based on a enum or a magic string...
But this is maybe a better solution...