What problems does reflection solve?

c#, reflection

Solution

It should be stated that .NET reflection isn't revolutionary - the concepts have been around in other framework.

Reflection in .NET has 2 facets:

Investigating type information

Without some kind of reflection / introspection API, it becomes very hard to perform things like serialization. Rather than having this provided at runtime (by inspecting the properties/fields/etc), you often need code-generation instead, i.e. code that explicitly knows how to serialize each of your types. Tedious, and painful if you want to serialize something that doesn't have a twin.

Likewise, there is nowhere to store additional metadata about properties etc, so you end up having lots of additional code, or external configuration files. Something as simple as being able to associate a friendly name with a property (via an attribute) is a huge win for UI code.

Metaprogramming

.NET reflection also provides a mechanism to create types (etc) at runtime, which is hugely powerful for some specific scenarios; the alternatives are:

- essentially running a parser/logic tree at runtime (rather than compiling the logic at runtime into executable code) - much slower

- yet more code generation - yay!

Problem

I went through all the posts on reflection but couldn't find the answer to my question. What were the problems in the programming world before .NET reflection came and how it solved those problems? Please explain with an example.

Original source