1

Let's say I have the following class:

public class Target
{
   public int field1;
   public int field2;
   public int Prop1 { get; set; }
   public int Prop2 { get; set; }
}

If I do a:

foreach(far f in typeof(Target).GetFields())
   Console.WriteLine(f.Name);

I would get the fields in the order they're declared in (field1 then field2). Same thing if I did GetProperties

Now, consider the following:

public class Target
{
   public int field1;
   public int Prop1 { get; set; }
   public int field2;
   public int Prop2 { get; set; }
}

When I did:

    var members = typeof(Target).GetMembers()
                 .Where(m => m.MemberType == MemberTypes.Field ||
                             m.MemberType == MemberTypes.Property);

    foreach (var m in members)
        Console.WriteLine(m.Name);

I got the following output:

Prop1
Prop2
field1
field2

Obviously, not in the order the members are declared in (which is field1, Prop1, field2 and Prop2)

Is there any way I can get the members in that order?

Thanks.

EDIT:

I care about the order, because I work with Unity3D (Game engine) and I'm writing a custom editor for a certain type. The type will have fields and properties, I want to draw the fields/properties in the order that they're declared in. Of course, unity does draw the fields in the order they're declared in, but it doesn't draw properties. That's why I'm making my own drawers/editors to support property drawing.

enter image description here

vexe
  • 5,433
  • 12
  • 52
  • 81
  • Sorry, but have to ask, is there a good reason not to make the fields properties to prevent this kind of problem? – Me.Name May 06 '14 at 09:18
  • Why are you concerned about the order? – Sriram Sakthivel May 06 '14 at 09:20
  • 4
    I believe the order the members come out in reflection (for any member type) is an implementation detail of the way the compiler writes the metadata into the generated assemblies. You shouldn't be relying on the order the members were declared, as again, this is an implementation detail. – Martin Costello May 06 '14 at 09:21
  • Edited, added the I care about the order. – vexe May 06 '14 at 09:40

0 Answers0