Search code examples
c#foreachpropertyinfo

Loop on GetFields and GetProperties of a Type?


Here is my code :

var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
    //some code
}

var props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
    //exact same code
}

I know I can create a function that I could call twice but what I'd like to do (if possible) is a single foreach. Something like this (yes, the code doesn't work. If it worked, I wouldn't ask the question !):

var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
var props = type.GetProperties();

foreach (PropertyInfo prop in fields && PropertyInfo prop in props)
{
    //some code
}

I really feel like there is a way, even if I know that my solution is far from being compilable :(
Thanks for any help !


Solution

  • If you're OK with properties exposed by MemberInfo class (which is base for both FieldInfo and PropertyInfo) then you may do the following:

    var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance).Cast<MemberInfo>();
    var props = type.GetProperties().Cast<MemberInfo>();
    var fieldsAndProperties = fields.Union(props);
    
    foreach (MemberInfo mi in fieldsAndProperties)
    {
    ...
    }