Search code examples
c#inheritancereflectionpropertiesderived-class

c# how to get list of derived class properties by reflection, ordered by base class properties first, and then derived class props


i am looking to get a list of properties from a derived class i wrote a function that gives my a list of properties. my problem is that i want the list of properties to contain first properties of base class and after properties of derived class how can i do this? now i get first properties in derived and then of base

PropertyInfo[] props = typeof(T).GetProperties();
        Dictionary<string, ColumnInfo> _colsDict = new Dictionary<string, ColumnInfo>();

        foreach (PropertyInfo prop in props)
        {
            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                ColumnInfo colInfoAttr = attr as ColumnInfo;
                if (colInfoAttr != null)
                {
                    string propName = prop.Name;
                    _colsDict.Add(propName, colInfoAttr);                        
                }
            }
        }

Solution

  • If you know the base class type, you can probably do something like this:

      public static Dictionary<string, object> GetProperties<Derived, Base>()
      {
            var onlyInterestedInTypes = new[] { typeof(Derived).Name, typeof(Base).Name };
    
            return Assembly
                .GetAssembly(typeof(Derived))
                .GetTypes()
                .Where(x => onlyInterestedInTypes.Contains(x.Name))
                .OrderBy(x => x.IsSubclassOf(typeof(Base)))
                .SelectMany(x => x.GetProperties())
                .GroupBy(x => x.Name)
                .Select(x => x.First())
                .ToDictionary(x => x.Name, x => (object)x.Name);
      }
    

    The important part for you being .OrderBy(x => x.IsSubclassOf(typeof(Base))) which will order the properties.