Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 216
Shin Avatar asked Mar 15 '13 18:03

Shin


People also ask

How do you know if a property is readonly?

With PropertyDescriptor , check IsReadOnly . With PropertyInfo , check CanWrite (and CanRead , for that matter). You may also want to check [ReadOnly(true)] in the case of PropertyInfo (but this is already handled with PropertyDescriptor ): ReadOnlyAttribute attrib = Attribute.

What is read only and write only properties C#?

Read-Only Properties: When property contains only get method. Write Only Properties: When property contains only set method. Auto Implemented Properties: When there is no additional logic in the property accessors and it introduce in C# 3.0.

Can property be readonly in C#?

Create Readonly Property Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor.


1 Answers

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");
}
like image 156
Martin Avatar answered Oct 30 '22 03:10

Martin