Nic Foster
Nic Foster

Reputation: 2894

Use Reflection to get PropertyInfo, only want to see accessors that have mutators

Using reflection I want to retrieve only the properties that have both a get and a set method, and ignore ones with only a get. What I'm trying to do is give the user a list of variables that he/she is able to change, so showing them properties that only have a get method is misleading.

Given this code below, the user would only be shown Name. Or I could possibly show them both, but grey-out UniqueID so they know they cannot change it.

public Int64 UniqueID
{
    get { return this.uniqueID; }
}

public String Name
{
    get { return this.name; }
    set { this.name = value; }
}

Background Info: I'm using C# 4.0.

Upvotes: 2

Views: 617

Answers (2)

M.Babcock
M.Babcock

Reputation: 18965

I think the property you are looking for is PropertyInfo.CanWrite and this can be implemented as the following to check both Get and Set with something like:

if (propInfo.CanWrite && propInfo.CanRead)

Upvotes: 3

Ani
Ani

Reputation: 113472

You can use the CanRead and CanWrite properties:

Type type = ...
var readWriteProps = type.GetProperties()
                         .Where(p => p.CanRead && p.CanWrite); 

Do note that the above query looks only for public properties with public accessors.

Upvotes: 4

Related Questions