Loading WinRT Types via Reflection in Windows 8

Loading WinRT Types via Reflection in Windows 8

Rate This
  • Comments 4

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:

typeof(Windows.Globalization.Language).AssemblyQualifiedName

which results in the following string:

"Windows.Globalization.Language, Windows.Globalization, Version=255.255.255.255, 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.

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

  • What's this "WP8" you speak of?

  • 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?

    Andy

  • 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.

Page 1 of 1 (4 items)