FPGA
FPGA

Reputation: 3865

What is the right way to get Public propertyinfo only?

is the following the most convenient way?

type.GetProperties().Where(pinfo=> pinfo.CanRead).ToArray();

all i want to do is to ignore the following

private object prop {get;set;}
protected object prop {get;set;}

but not

public object prop {get;set;}
public object prop {get;private set;}

Upvotes: 0

Views: 247

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

Isn't that simply GetProperties? By default you'll get only public properties.

var properties = type.GetProperties();

Note: This includes static properties and write-only properties also, but I believe no one design a property with set only accessor.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

There is an overload which takes BindingFlags as an argument: Type.GetProperties Method (BindingFlags).

type.GetProperties(BindingFlags.Public | BindingFlags.Instance)

Quick test shows it returns exactly what you need:

public class TestClass
{
    private object prop1 { get; set; }
    protected object prop2 { get; set; }

    public object prop3 { get; set; }
    public object prop4 { get; private set; }
}
var prop = typeof(TestClass).GetProperties(BindingFlags.Instance | BindingFlags.Public);

Return 2 elements: prop3 and prop4 properties.

Upvotes: 3

Related Questions