23

I'm trying to port a simple application to Windows 8 Metro (WinRT). It seems that some very basic methods are missing. One basic example: Type.GetProperty(). It is available for Windows Phone 7, Silverlight and .NET client profile. Do I have to install something (eg. a special library) or is this method simply not available in the .NET metro profile?

UPDATE

OK, thank you. Now I use this.GetType().GetTypeInfo().DeclaredProperties.

using System.Reflection; is needed to have this GetTypeInfo() extension method.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Rico Suter
  • 11,548
  • 6
  • 67
  • 93
  • Sidenote: It is not that simple to port an existing WP7 app to metro. There are not only namespace changes... (Reflection, Streams, Dispatcher, ...) – Rico Suter Oct 22 '11 at 13:37

2 Answers2

24

Reflection has changed a bit in Metro: see MSDN ( "Reflection changes" - near the bottom ).

Basically, you now need: type.GetTypeInfo().

Nick Butler
  • 24,045
  • 4
  • 49
  • 70
12

In addition to Nicholas Butler response, I ended up using this kind of extensions to maintain the code reusable in all platforms.

#if NETFX_CORE // Workaround for .Net for Windows Store not having Type.GetProperty method
    public static class GetPropertyHelper
    {
        public static PropertyInfo GetProperty(this Type type, string propertyName)
        {
            return type.GetTypeInfo().GetDeclaredProperty(propertyName);
        }
    }
#endif

This way, Type.GetProperty() is implemented for all platforms.

redent84
  • 18,901
  • 4
  • 62
  • 85
  • Granted, this is an old thread, but I should like to add that GetDeclaredPropert(y/ies) will only return properties on current type. Meaning that if Class2 derives from Class1, GetDerivedProperties will only return properties from Class2. – Falgantil Nov 26 '14 at 16:19
  • @BjarkeSøgaard if you want to search in all properties you can use `type.GetRuntimeProperty(propertyName)` – redent84 Nov 26 '14 at 18:09
  • Actually I ended up just doing this: for (; type != null; type = type.GetTypeInfo().BaseType) – Falgantil Nov 27 '14 at 08:35
  • 1
    How about GetProperties()? – Vahid Dec 28 '14 at 11:07
  • 1
    @BjarkeSøgaard Have you tried `GetType().GetRuntimeProperties()`? – redent84 Dec 28 '14 at 17:59