Loading WinRT Types via Reflection in Windows 8

Hopefully this will get added to the documentation eventually, but recently I was playing around with some reflection code in Windows 8 Consumer Preview and a few web searches for the “obvious” keywords didn’t yield any results, so I thought I’d post this up in case anyone else falls into the same boat. It’s not rocket science to figure out, but maybe this will help someone anyway.

Say you want to create a Windows.Globalization.Language object via reflection and get its DisplayName. You can use the following:

using System.Reflection; // Needed for GetTypeInfo extension method

var t = Type.GetType(“Windows.Globalization.Language, Windows, ContentType=WindowsRuntime”);
var lang = Activator.CreateInstance(t, new[] { “en-US” }); ;
var name = t.GetTypeInfo().GetDeclaredProperty(“DisplayName”).GetValue(lang);

Deducing this was easy, by looking at the result of the following property evaluation in the Immediate window:


which results in the following string:

“Windows.Globalization.Language, Windows.Globalization, Version=, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime”

and a bit of trial and error gets rid of the extraneous bits (including the ‘Globalization’ part of the assembly name). So far, all the examples I have tried have worked simply by appending “, Windows, ContentType=WindowsRuntime” to the type name, but obviously your mileage may vary (and this could change by RTM).

Note that you need the using System.Reflection line since GetTypeInfo is an extension method as part of the refactored “.NET for Metro-style apps” profile.

Comments (4)

  1. OMG! says:

    He has returned!  Now tell us what we can keep now that WP8 has changed everything all over again.

  2. ptorr says:

    What's this "WP8" you speak of?

  3. Andy Wilkinson says:

    Hi Peter,

    Do you have any idea what the Windows Store certification process is going to think of creating types via reflection. I have an app framework (cocoon.codeplex.com) using reflection that passes the current automated tests in the Consumer Preview bits fine – but in the future? and if I were to do reflection into private fields? or are you still okay since you are accessing everything critical via the broker process?


  4. ptorr says:

    Andy, I'm afraid I can't speak about the Windows Store policies, because I don't know what they will be. Nevertheless I assume that since Reflection is in the Metro-styled subset that you are OK to use it.