Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering out protected setters when type.GetProperties()

I am trying to reflect over a type, and get only the properties with public setters. This doesn't seem to be working for me. In the example LinqPad script below, 'Id' and 'InternalId' are returned along with 'Hello'. What can I do to filter them out?

void Main()
{
    typeof(X).GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
    .Select (x => x.Name).Dump();
}

public class X
{
    public virtual int Id { get; protected set;}
    public virtual int InternalId { get; protected internal set;}
    public virtual string Hello { get; set;}
}
like image 726
mcintyre321 Avatar asked Sep 26 '11 17:09

mcintyre321


1 Answers

You can use the GetSetMethod() to determine whether the setter is public or not.

For example:

typeof(X).GetProperties(BindingFlags.SetProperty |
                        BindingFlags.Public |
                        BindingFlags.Instance)
    .Where(prop => prop.GetSetMethod() != null)
    .Select (x => x.Name).Dump();

The GetSetMethod() returns the public setter of the method, if it doesn't have one it returns null.

Since the property may have different visibility than the setter it is required to filter by the setter method visibility.

like image 82
Elisha Avatar answered Oct 18 '22 23:10

Elisha