Striding Dragon
Striding Dragon

Reputation: 243

Find object properties of a certain type

I am trying to recursively build a list of all the fields of an object that are of a certain type. Recursion is needed because the object can hold arrays of objects which, in turn, may contain fields of a certain type.

So, if an object has a field of type Wanted, I want that object in the list.

class a
{
    Wanted m_var;
};

If an object has an array that contains other objects and these objects contain a field of type Wanted, I'd also like those added to the list.

class b
{
    int m_whatever;
    a[] m_vararray;
};

I've been trying all sorts of approaches, including Reflection but I am not getting anywhere. All the attempts were some variation of this

private IList<object> ListOfTypeWanted(object fields)
{
    IList<object> result = new List<object>();

    System.Reflection.MemberInfo info = fields.GetType();
    object[] properties = type.GetProperties();

    foreach (var p in properties)
    {
        if (true == p.GetType().IsArray)
        {
            result.Add(ListOfTypeWanted(p));
        }
        else
        {
            Type t = p.GetType();
            if (p is WantedType)
            {
                result.Add(this);
            }
        }
    }
    return result;
}

I've also tried Linq statements using Where() but they did not get me any useful results either.

Does anyone know what the best way is to achieve this?

Upvotes: 0

Views: 56

Answers (1)

cathei
cathei

Reputation: 609

Your question contains many typo and syntax error, but I can advise few:

  1. Make sure you want GetProperties not GetFields. Your example seems like you only have fields, not properties.
  2. Make sure you are providing proper BindingFlags when calling GetProperties. Your example seems like containing private member. In that case BindingFlags.NonPublic | BindingFlags.Instance should be used.

Upvotes: 1

Related Questions