.Net 4.5 Reflection API Changes

I’m a little behind on the game, but it looks like the .Net Reflection APIs changed in 4.5 http://t.co/7PYN1e3ksN
— Carlo Wahlstedt (@carlowahlstedt) January 29, 2015

Thought I’d share a few examples of changes when converting to .Net 4.5. The pre-4.5 version is on top and the 4.5 version is on the bottom.

GetRuntimeMethods

typeof(Extensions).GetMethod("methodName")

typeof(Extensions).GetRuntimeMethods().Where(t => t.Name == "methodName").FirstOrDefault()

GetRuntimeProperties

item.GetType().GetMember("memberName");

item.GetType().GetRuntimeProperties().Where(t => t.Name == "memberName");
and
item.GetType().GetProperties();

item.GetType().GetRuntimeProperties();

GetTypeInfo – Extension

Make sure you add a using for System.Reflection

memberExpression.Member.DeclaringType.IsAssignableFrom(item.GetType())

memberExpression.Member.DeclaringType.GetTypeInfo().IsAssignableFrom(item.GetType().GetTypeInfo())

GetCustomAttribute

(CustomCreatedAttribute)Attribute.GetCustomAttribute(item.GetType(), typeof(CustomCreatedAttribute));

item.GetType().GetTypeInfo().GetCustomAttribute<CustomCreatedAttribute>();
Tagged with: