Filtering protected setters when type.GetProperties ()

I'm trying to think about a type and get only properties with public setters. This does not seem to work for me. In the example below, the LinqPad script, '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;} } 
+4
source share
1 answer

You can use GetSetMethod () to determine if the setter is publicly available or not.

For instance:

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

GetSetMethod() returns a public method installer; if it does not have it, it returns null .

Since the property may have different visibility than the setting tool, it must be filtered by the visibility of the setter method.

+4
source

All Articles