Ruker
Ruker

Reputation: 15

List all Public Properties of a Class

In one class I have defined Auto-Propertys, which I like to use later in list together with values.

My current code:

int klength = usbconf.GetType().GetProperties().Length;

for (int k = 0; k < klength-2; k++)
{
     var prop = usbconf.GetType().GetProperties();

     readinglist.Add(new MyList()
     {
          DataTag = (DataEnums)Enum.Parse(typeof(DataEnums), prop[k].Name),
          WriteByteArray = (byte[])prop[k].GetValue(usbconf),
     });
}

Where the length is 56 and not 54, like I want to have (54 is a magic number of public variables in my special class:)). There is also listet "DisplayName" and "ThrowOnInvalidPropertyName" which I didnt define it. How to limit "Length" on 54 - choosing only the Public one without "DisplayName" and "ThrowOnInvalidPropertyName".

I already try that:

var bindingFlags = BindingFlags.Public;

int klength = usbconf.GetType().GetProperties(bindingFlags).Length;

for (int k = 0; k < klength-2; k++)
{
     var prop = usbconf.GetType().GetProperties(bindingFlags);

     readinglist.Add(new MyList()
     {
          DataTag = (DataEnums)Enum.Parse(typeof(DataEnums), prop[k].Name),
          WriteByteArray = (byte[])prop[k].GetValue(usbconf),
     });
}

However, I don't get any results, and Length is returning 0. If there any questions, please ask.

Upvotes: 0

Views: 1076

Answers (2)

Luaan
Luaan

Reputation: 63742

The binding flags you want are

BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly

These mean:

  • Public - list public members
  • Instance - list instance members
  • DeclaredOnly - list only the members defined on the exact type, disregarding any inherited members

Most likely, the DisplayName and ThrowOnInvalidPropertyName properties are inherited from your base class - adding DeclaredOnly filters them out (but do note that it also means that if you derive a new class from your class, you'll again only get the members defined there and not the inherited ones).

Upvotes: 2

Dirk Vollmar
Dirk Vollmar

Reputation: 176169

You can simply iterate over all public properties and just skip the ones you are not interested in:

foreach (var propertyInfo in usbconf.GetType().GetProperties())
{
    if (propertyInfo.Name.Equals("DisplayName")
        || propertyInfo.Name.Equals("ThrowOnInvalidPropertyName"))
    {
        continue;
    }

    // your loop body goes here
}

Upvotes: 1

Related Questions