9

I need to get a list of properties from MyClass, excluding 'readonly' ones, can I get 'em?

public class MyClass
{
   public string Name { get; set; }
   public int Tracks { get; set; }
   public int Count { get; }
   public DateTime SomeDate { set; }
}

public class AnotherClass
{
    public void Some()
    {
        MyClass c = new MyClass();

        PropertyInfo[] myProperties = c.GetType().
                                      GetProperties(BindingFlags.Public |
                                                    BindingFlags.SetProperty |
                                                    BindingFlags.Instance);
        // what combination of flags should I use to get 'readonly' (or 'writeonly')
        // properties?
    }
}

And last, coluld I get 'em sorted?, I know adding OrderBy<>, but how? I'm just using extensions. Thanks in advance.

Shin
  • 664
  • 2
  • 13
  • 30

1 Answers1

13

You can't use BindingFlags to specify either read-only or write-only properties, but you can enumerate the returned properties and then test the CanRead and CanWrite properties of PropertyInfo, as so:

PropertyInfo[] myProperties = c.GetType().GetProperties(BindingFlags.Public |
                                                    BindingFlags.SetProperty |
                                                    BindingFlags.Instance);

foreach (PropertyInfo item in myProperties)
{
    if (item.CanRead)
        Console.Write("Can read");

    if (item.CanWrite)
        Console.Write("Can write");
}
Martin
  • 16,093
  • 1
  • 29
  • 48
  • Apologies, I forgot the sorting request - how do you want them sorted? By read\write, read-only, write-only, or by name, etc? – Martin Mar 15 '13 at 18:20
  • If you can show examples for all you say, I'll be pretty thankful. – Shin Mar 15 '13 at 18:33
  • 4
    I got it now, PropertyInfo[] ... .Where(p => p.CanWrite).OrderBy(x => x.Name).ToArray(); – Shin Mar 15 '13 at 19:10
  • 1
    It's not useful to include `BindingFlags.SetProperty` in this context, is it? Other than that, `GetProperties().Where(p => p.CanWrite)` or maybe `Where(p => p.CanRead && p.CanWrite)` is a good solution. – Jeppe Stig Nielsen Mar 15 '13 at 19:30