Dealing with types in WinRT

Another quick tip: Most of the interaction with the System.Type class in Windows 8 is now done through the TypeInfo class. An instance of TypeInfo for a give type is retrieved using an extension method called GetTypeInfo(). Note that since this is an extension method, it will not be visible in Intellisense unless you add a reference to System.Reflection in the “using” section:

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

(...)

var info = myType.GetTypeInfo();

// Was: string name = myType.Name
string name = info.Name;

// Was: Type[] interfaces = myType.GetInterfaces();
IEnumerable<Type> interfaces = info.ImplementedInterfaces;

// Was: bool check = myType.IsSubclassOf(anotherType);
bool check = anotherType.GetTypeInfo().IsAssignableFrom(info);

(etc...)

Note: IsSubclassOf and IsAssignableFrom do not have the exact same meaning, however in many cases it should be able to use IsAssignableFrom. Make sure to check the documentation to verify that this is indeed what you want!

Hopefully this is useful to WinRT coders out there!

Laurent

 

Print | posted on Sunday, September 25, 2011 8:35 PM

Feedback

# re: Dealing with types in WinRT

left by James Manning at 10/3/2011 6:18 AM Gravatar
Sorry for my confusion, but I don't quite get why this is called a WinRT thing? AFAICT TypeInfo is a new class in .NET 4.5 (as per http://msdn.microsoft.com/en-us/library/system.reflection.typeinfo(v=VS.110).aspx) and as such is available for anyone using .NET 4.5, regardless of whether they're on Win8 (where WinRT runs) or not?

Apologies if I'm just missing something. :)

Thanks!

# re: Dealing with types in WinRT

left by Laurent at 10/6/2011 11:59 AM Gravatar
Hi,

Yes you are right. I should have been more precise: In WinRT, the TypeInfo class is *the only way* to get the information about the Type.

Cheers and thanks,
Laurent
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: