0

I have some generated classes which are similar in form but have no inheritance relationships, like this:

class horse {}
class horses { public horse[] horse {get;}}
class dog {}
class dogs { public dog[] dog {get;}}
class cat {}
class cats { public cat[] cat {get;}}

I want to write a method like:

ProcessAnimals<T>(Object o)
{
 find an array property of type T[]
 iterate the array
}

So then I might do:

horses horses = ...;
ProcessAnimals<horse>(horses);

It seems like something reflection can be used for but what would that look like?

1
  • Loop through the properties using reflection, examining the IsArray property on each property's type. Commented Oct 19, 2016 at 14:02

2 Answers 2

1

You can iterate over the properties checking for arrays type:

void ProcessAnimals<T>(object o)
{
    var type = o.GetType();

    var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    .Where(pi => pi.PropertyType.IsArray && pi.PropertyType.GetElementType().Equals(typeof(T)));

    foreach (var prop in props)
    {
        var array = (T[])prop.GetValue(o);

        foreach (var item in array)
        {
            //Do something
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can I ask for clarification on the BindingFlags detail?
it's to check for properties that are public and instance type. To exclude for example protected and static properties.
0

I can suggest other way of doing this, without reflection, because all of this classes are basically the same:

enum AnimalType
{
Horse,
Dog,
Cat
}
class Animal
{
public AnimalType Type;
}
class Animals
{
public Animal[] Animals { get; }
}
ProcessAnimals(Animals animals)
{
// do something with animals.Animals array
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.