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.
I guess that a "stand alone" application, where every object you use is known at compile time, you don't use reflection much.
But when you write library or framework code that should use objects that are not known (completely - you might know about interfaces or baseclasses) at compile time, reflection could be invaluable to work with those objects.
Generally speaking Reflection allows you access to metadata about objects. Combining Reflection with other techniques allows you to make your program more dynamic. For instance you can load a DLL and determine if it contains an implementation of an interface. You could use this to discover dll's that support functionality at runtime. Use could use this to extend an application without a recompilation and without having to restart it.
Intellisense in Visual Studio uses reflection to give you information about the objects you are using.
Note that using Reflection comes at a cost. Reflecting an object can be slow. But if you need it Reflection is a very usefull tool.
Here are some things I've used Reflection for that would be extremely difficult or impossible without it:
The Managed Extensibility Framework (a new .NET library) uses reflection to:
I recently used it to add custom attributes to fields in my enum:
Using reflection to get the field:
The attribute class:
One use among many: you can make a plug-in architecture where you specify the name of the class-to-use in a configuration file. Using reflection you can take this string and create an instance of the object requested. If that object implements a known interface, then you can use it through ordinary (non reflection) code.
I've used reflection to allow me more flexibility meeting constantly changing requirements. That is, the customer kept changing their minds as to where to place a database table within a database. All I did was have the object self inspect its fields and call the object constructors of those fields within the object itself. Then, if one table should be found somewhere else? Click, paste, done.
This did not go out in final production, mind you, but during the iterative phase removed some of the boilerplate I would need to change.