20 June 2012

Reflection in WinRT: DeclaredProperties vs GetRuntimeProperties caveat

I suppose this is part of some FM I did not R, but I would like to point it out in case some other sod wastes just as much time on it as me.

I embarked upon a journey to port SilverlightSerializer and some behaviors to WinRT. All stuff is heavily making use of reflection. Now reflection has been hugely overhauled in WinRT, so I knew I was in for an interesting ride. Recently I was convinced I managed to do it, but it turned out I did not.

There are apparently two ways to use reflection in RT. What I did use for reading all properties of an object, was:

var properties = MyObject.GetType().GetTypeInfo().DeclaredProperties;

But it turns out this returns only the properties declared in the class itself. What it does not return, are the properties of possible parent classes!

What I should have used, apparently, is:

var allproperties = MyObject.GetType().GetRuntimeProperties();

When I feed a Grid into “MyObject”,  “properties” hold 6 properties, while “allproperties” holds 51.

I don’t know why this distinction is made, and I understand even less how come I missed this the first time. On my first meeting as an MVP, Dennis Vroegop, after welcoming me to the club, already warned me that the MVP award did not automatically come with super powers. Boy, was he right.

1 comment:

Dennis Doomen said...

That's something we ran into while working on the Metro version of Fluent Assertions. We wrapped those calls in some generic extension methods. See
http://fluentassertions.codeplex.com/SourceControl/changeset/view/79081#1587054