how do I iterate through internal properties in c#
Solution 1
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.
Solution 2
You need to change the BindingFlags
on your call to Type.GetProperties
Try:
var instanceProperties = typeof(TestClass).GetProperties(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance
);
foreach(var instanceProperty in instanceProperties) {
// a little something something for the instanceProperty
}
Solution 3
According to MSDN, private and internal are not recognized in Reflection API.
To identify an internal method using Reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly.
If You are writing some test units You might want to take a look at InternalsVisibleTo attribute. It allows you to specify which assembly can see internal properties.
And finally, do You really need to have internal properties...
Solution 4
by specifying what bindingflags in GetProperties:
foreach (PropertyInfo property in typeof(TestClass).GetProperties(
BindingFlags.Instance|
BindingFlags.Public|
BindingFlags.NonPublic))
Solution 5
Use BindingFlags
foreach (PropertyInfo property in typeof(TestClass)
.GetProperties(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance))
{
//do something
}
coder
As of Sep 2011, I'm working with C#, Silverlight 4, WCF, objective-c
Updated on July 09, 2020Comments
-
coder almost 4 years
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 }
-
Marcin Deptuła over 12 yearsGiving NonPublic and Instance will hide prop 1 and prop 2, you need both, NonPublic | Public for all properties
-
coder over 12 yearsyeah, I had to add BindingFlags.Public as well
-
coder over 12 yearsyeah I do, it's wcf service class, I want the client to fill in some properties before sending it to the server, and rest of the properties to be filled in on the service.
-
Neville Nazerane over 6 yearsanyway to select only protected or internal?
-
Jon Skeet over 6 years@NevilleNazerane: Not with binding flags, that I'm aware of. Just filter afterwards.