Home > OS >  Use reflection to get all public properties in poco class not including enum property
Use reflection to get all public properties in poco class not including enum property

Time:11-05

I'm using reflection to retrieve all of the public properties of a poco class

poco e.g.

 public class MetaData
    {
        [ExplicitKey]
        public string Id{ get; set; }

        
        public enum DataType
        {
            T1 = 1,
            T2 = 2,
            T3 = 3
        }
        
        public DataType MyDataType { get; private set; } //<- enum
        
        public string ParentFolder { get; private set; }

        public string FileName { get; private set; }
...

Using reflection to obtain all of those properties seems to always exclude the enum property: e.q.

var publicPropertiesUsed = metaData.GetType().GetProperties().Where(x => x.PropertyType.IsPublic);

When interrogating the enum property, IsPublic is false.

What's the correct way to obtain all the public properties through reflection?

CodePudding user response:

Your DataType enum is nested within your MetaData class. In such case IsPublic returns false.

From the IsPublic documentation

true if the Type is declared public and is not a nested type; otherwise, false.

Either move that enum outside that MetaData class or use IsVisible instead of IsPublic.

From the IsVisble documentation

true if the current Type is a public type or a public nested type such that all the enclosing types are public; otherwise, false.

var publicPropertiesUsed = 
    metaData.GetType()
        .GetProperties()
        .Where(x => x.PropertyType.IsVisble);
  • Related