.netreflectionmethodinfopropertyinfo

Finding the hosting PropertyInfo from the MethodInfo of getter/setter


I do some type analysis in runtime using Reflection. If I have a MethodInfo instance, how can I figure out if this is a "real" method or is a getter/setter method of a property? And if it is a property, how can I find the its hosting PropertyInfo back?


Solution

  • Ecma 335 specifies (but does not demand) that compilers use the get_/set_ prefixes (chapter 22.28). I don't know any language that breaks that recommendation. Making it easy:

    public static PropertyInfo GetPropFromMethod(Type t, MethodInfo method) {
      if (!method.IsSpecialName) return null;
      return t.GetProperty(method.Name.Substring(4), 
        BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
    }