Ian Vink
Ian Vink

Reputation: 68750

Properties in a particular order

Using reflection I have a tool that gets the properties of a class:

foreach (MemberInfo member in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
    WriteValue(streamWriter, member.Name);
}

Is there a way to ask "GetProperties" to return MemberInfo's in the order they are defined in the class. I seriously doubt it, but thought I'd ask.

class Person
{
     public int Id { get; set; }
     public int Age { get; set; }
}

I'd like to get MemberInfo's in this order then: Id, Age

Upvotes: 4

Views: 118

Answers (2)

user1416420
user1416420

Reputation: 498

[Caution: use at your own discresion as these are obviously Microsoft's impl details, which may change in future releases]

Update: Mono seems to work too

I've observed consitent behaviour using MS compilers since v3.5 when I stumbled upon this:

using System;
using System.Linq;
using System.Reflection;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {    
            typeof(Test).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                .OrderBy(member => member.MetadataToken).ToList()
                .ForEach(member => Console.WriteLine(member.Name));

            Console.ReadLine();
        }
    }

    public class Test
    {
        public int SecondProperty { get; set; }
        public int FirstProperty { get; set; }

    }
}

Upvotes: 2

Anton Tykhyy
Anton Tykhyy

Reputation: 20076

No, for auto-properties there isn't. You can get methods in order of declaration using debug symbols, and since property getters are methods, you can (with some work) obtain a list of properties with explicit getters (or setters) in order of declaration, but the getters of auto-properties have no source code and thus no debug symbols to indicate their location. As for CLI metadata, the compiler is not obliged to put them in order of declaration, and as reflection relies exclusively on metadata, it cannot be used for this purpose.

Upvotes: 1

Related Questions