C# Get FieldInfos/PropertyInfos in the original order?

http://msdn.microsoft.com/en-us/library/ch9714z3.aspx

The GetFields method does not return fields in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which fields are returned, because that order varies.

http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx

The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which properties are returned, because that order varies.

You would need to define order yourself, perhaps with attributes:

class Test
{
    [Order(1)] public bool First { get; set; }
    [Order(2)] public int Second;
    [Order(3)] public string Third { get; set; }
}
...
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, 
    Inherited = true, AllowMultiple = false)]
[ImmutableObject(true)]
public sealed class OrderAttribute : Attribute {
    private readonly int order;
    public int Order { get { return order; } }
    public OrderAttribute(int order) {this.order = order;}
}

Leave a Comment