obiwanjacobi
obiwanjacobi

Reputation: 2463

How can I determine the accessibility of a MemberInfo instance?

I know the BindingFlags are used to fetch public and non-public members from a Type.

But is there a way to determine if a MemberInfo instance (or derived like PropertyInfo, MethodInfo) is public or not (after it was returned from one of the methods on Type)?

Upvotes: 13

Views: 1284

Answers (2)

kofifus
kofifus

Reputation: 19305

You can try ie:

var isPublic = memberInfo.MemberType switch
{
  MemberTypes.Field => ((FieldInfo)memberInfo).IsPublic,
  MemberTypes.Property => ((PropertyInfo)memberInfo).GetAccessors().Any(MethodInfo => MethodInfo.IsPublic),
  _ => false
};

For properties this return true if there is any public accessor which I think is what you're after

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502816

PropertyInfo, MethodBase etc each have an Attributes property which has this information - but there's nothing in MemberInfo, because each kind of member has its own kind of attributes enum. Hideous as it is, I think you may need to treat each subclass of MemberInfo separately :( You can probably switch on MemberInfo.MemberType and then cast, which will be slightly nicer than lots of as/test-for-null branches, but it's still not ideal :(

if (member.MemberType == MemberTypes.Property)
{
    var property = (PropertyInfo) member;
    ...
}

Upvotes: 9

Related Questions