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.