Shin
Shin

Reputation: 673

How to get 'ReadOnly' or 'WriteOnly' properties from a class?

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.

Upvotes: 9

Views: 5444

Answers (1)

Martin
Martin

Reputation: 16433

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");
}

Upvotes: 13

Related Questions