Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reflection to get properties of a base class before properties of the derived class

public class BaseDto
{
    public int ID{ get; set; }
}
public class Client: BaseDto
{
     public string Surname { get; set; }
     public string FirstName{ get; set; }
     public string email{ get; set; }    
}

PropertyInfo[] props = typeof(Client).GetProperties();

This will list the properties in this order: Surname, FirstName, email, ID

Want the properties to display in this order: ID, Surname, FirstName, email

like image 427
stig-red Avatar asked Nov 15 '13 07:11

stig-red


2 Answers

Maybe this ?

// this is alternative for typeof(T).GetProperties()
// that returns base class properties before inherited class properties
protected PropertyInfo[] GetBasePropertiesFirst(Type type)
{
    var orderList = new List<Type>();
    var iteratingType = type;
    do
    {
        orderList.Insert(0, iteratingType);
        iteratingType = iteratingType.BaseType;
    } while (iteratingType != null);

    var props = type.GetProperties()
        .OrderBy(x => orderList.IndexOf(x.DeclaringType))
        .ToArray();

    return props;
}
like image 112
Sriram Sakthivel Avatar answered Sep 22 '22 02:09

Sriram Sakthivel


Not sure if there is a quicker way to do it, but first, get the type of the base type that you inherit from.

    typeof(Client).BaseType

After that you can get only the base properties using bindingflags.

    BindingFlags.DeclaredOnly

After that do the same for the Client type, and append the result.

like image 23
Eugène Avatar answered Sep 21 '22 02:09

Eugène