Tuesday, May 20, 2008

Powerful reflection

I'm sorry to disappoint most of you, but this is not a deeply psycho-analytic and philosophical self-reflection post. I'm afraid I'm going to turn most of you away when I tell you it's about one of the strongest features I've ever seen in C#, a programming language.

I knew that C# had something called 'Reflection', which you could use to determine object types and other 'compile-time' information, but then at 'run-time'. I never did use it, though, until now. It's kind of amazing to see what you can do with that stuff!

I'm currently writing a serializer/deserializer (read from and write to xml files) using reflection, and I have managed to keep 95% of the code within one single class, and the remaining 5% in a single function within each 'object manager' (special dictionaries which stores and retrieves top-level components - I currently have 3 of those). None of my objects actually being saved have any serialization code whatsoever, save for a simple [Serialize] attribute which I attach to each property that I would like to see saved and loaded.

And this code can already traverse the managers, writing out each object with public [Serialize]-able properties (in the case of simple types or references to other 'managed' objects), nested objects, and lists of properties/objects.

For reference's sake, the main serialization class is about 150 lines long (pure code, excluding whitespace and comments). Beautiful, isn't it?

No comments: