Skip to content

Instantly share code, notes, and snippets.

@garyjohnson
Created April 22, 2012 14:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save garyjohnson/2464327 to your computer and use it in GitHub Desktop.
Save garyjohnson/2464327 to your computer and use it in GitHub Desktop.
WinRT Reflection Extension Methods
using System;
using System.Reflection;
namespace SharpSerializer
{
public static class ExtensionMethods
{
public static PropertyInfo GetProperty(this Type type, String propertyName)
{
return type.GetTypeInfo().GetDeclaredProperty(propertyName);
}
public static MethodInfo GetMethod(this Type type, String methodName)
{
return type.GetTypeInfo().GetDeclaredMethod(methodName);
}
public static bool IsSubclassOf(this Type type, Type parentType)
{
return type.GetTypeInfo().IsSubclassOf(parentType);
}
public static bool IsAssignableFrom(this Type type, Type parentType)
{
return type.GetTypeInfo().IsAssignableFrom(parentType.GetTypeInfo());
}
public static bool IsEnum(this Type type)
{
return type.GetTypeInfo().IsEnum;
}
public static bool IsPrimitive(this Type type)
{
return type.GetTypeInfo().IsPrimitive;
}
public static Type GetBaseType(this Type type)
{
return type.GetTypeInfo().BaseType;
}
public static bool IsGenericType(this Type type)
{
return type.GetTypeInfo().IsGenericType;
}
public static Type[] GetGenericArguments(this Type type)
{
return type.GetTypeInfo().GenericTypeArguments;
}
public static object GetPropertyValue(this Object instance, string propertyValue)
{
return instance.GetType().GetTypeInfo().GetDeclaredProperty(propertyValue).GetValue(instance);
}
public static TypeInfo GetTypeInfo(this Type type)
{
IReflectableType reflectableType = (IReflectableType)type;
return reflectableType.GetTypeInfo();
}
}
}
@rodrigoratan
Copy link

I was getting some null reference exceptions on the GetDeclaredProperty call, so I refactored it and the exceptions stopped, just in case i added a try catch :)
Hope it helps, i'm new on this github thing so I won't contribute oficially yet, lol

public static object GetPropertyValue(this Object instance, string propertyValue)
{
try
{
PropertyInfo pi = instance.GetType().GetTypeInfo().GetDeclaredProperty(propertyValue);
return pi != null ? pi.GetValue(instance) : null;
}
catch
{
return null;
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment