how do I iterate through internal properties in c#

GaneshT picture GaneshT · Sep 27, 2011 · Viewed 20.6k times · Source
public class TestClass
{
        public string property1 { get; set; }
        public string property2 { get; set; }

        internal string property3 { get; set; }
        internal string property4 { get; set; }
        internal string property5 { get; set; }
}

I can iterate through the properties with the following loop, but it only shows public properties. I need all the properties.

foreach (PropertyInfo property in typeof(TestClass).GetProperties())
{
    //do something
}

Answer

Jon Skeet picture Jon Skeet · Sep 27, 2011

You need to specify that you don't just need the public properties, using the overload accepting BindingFlags:

foreach (PropertyInfo property in typeof(TestClass)
             .GetProperties(BindingFlags.Instance | 
                            BindingFlags.NonPublic |
                            BindingFlags.Public))
{
    //do something
}

Add BindingFlags.Static if you want to include static properties.

The parameterless overload only returns public properties.