Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I iterate through internal properties in c#

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 } 
like image 945
GaneshT Avatar asked Sep 27 '11 20:09

GaneshT


People also ask

Which method is used to iterate through the items in the collection?

An iterator method or get accessor performs a custom iteration over a collection. An iterator method uses the yield return statement to return each element one at a time.

What is reflection C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


1 Answers

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.

like image 160
Jon Skeet Avatar answered Oct 17 '22 20:10

Jon Skeet