Reflecting on reflection
I have a sort of love-hate relationship with .NET reflection. Being a form of indirect programming, reflection is not as fast as early-bound code. However, that is a secondary point to me. Avoiding any performance-related gripes, my points about reflection are the following:
- I love the flexibility that reflection provides
- I hate the messy code it forces you to write
Reflection-based code is hard to read and maintain. So far I've been able to make use of reflection only to build infrastructural code--not directly application code. Love to see your thoughts about reflection and scenarios in which you're using it and comments you want to share.
Why reflection today? I'm working on a possible implementation of themes in ASP.NET 1.1.
I have a text file representing the skin to apply to all controls of a certain type. The text file lists a group of property/value pairs. For example,
<button>
<property>BackColor</property>
<value>Color.Gainsboro</value>
</button>
where BackColor is the property name and Color.Gainsboro is the corresponding value. Now imagine that you have some runtime code that loops through the controls of a page and applies to each control the skin settings. You can use reflection to set the BackColor property of a Button to a certain color. Sure, it is possible but you need to:
- Retrieve the PropertyInfo object for the property
- Set the value making sure that you pass in an expression of the proper type.
The second point is the harder I think.
So I discarded reflection and opted for code generation much like you do in a .NET project when you reference a Web service. You import the WSDL and the project generates the proxy file for you. That's what I did and it works. The drawback is that I currently lack tools integrated in VS.NET to automate the process.
There's a better option though and it is just what ASP.NET 2.0 does. In that case, with a significant help from the new compilation model. The idea is generating the code for the theme object at runtime. You look at files in theme directory, parse them in a VB/C# source and compile on the fly. Next, you load the assembly in the app.
It is not for the faint-hearted but it gets the better of both world--early-binding and flexibility.
Haven't started coding yet...