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.
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.
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.
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With