Get Actual Type from MemberInfo - CSharp System.Reflection

CSharp examples for System.Reflection:MethodInfo

Description

Get Actual Type from MemberInfo

Demo Code


using System.Reflection;
using System.Linq;
using System.Collections.Generic;
using System;//  w ww.j  a v a 2 s  .c  om

public class Main{
    public static Type GetActualType(this MemberInfo member)
      {
         Type rawType;
         if (!(member is Type))
         {
            rawType = member.GetVariableType();
         }
         else
         {
            rawType = (Type)member;
         }

         Type memberType;
         if (rawType.IsArray)
         {
            memberType = rawType.GetElementType();
            if (memberType == null)
            {
               throw new Exception(string.Format("Unable to get Type of Array {0} ({1}).", rawType, member.GetFullMemberName()));
            }
         }
         else
         {
            memberType = rawType;
         }
         return memberType;
      }
    public static Type GetVariableType(this MemberInfo member)
      {
         if (member is FieldInfo)
         {
            return ((FieldInfo)member).FieldType;
         }
         if (member is PropertyInfo)
         {
            return ((PropertyInfo)member).PropertyType;
         }
         throw new Exception("Can only get VariableType of Fields and Properties");
      }
    public static string GetFullMemberName(this MemberInfo member)
      {
         var str = member.DeclaringType.FullName + "." + member.Name;
         if (member is MethodInfo)
         {
            str += "(" + ((MethodInfo)member).GetParameters().ToString(", ", (param) => param.ParameterType.Name) + (")");
         }
         return str;
      }
}

Related Tutorials