Reflection and Generics, Collections, etc...

I

INeedADip

What I am trying to do is a sort of Recursion "search" or listing of all the
properties of a type.
If I have a class that looks like:

public class MyClass
{
private string _name = "jeff";
private int _age = 22;
private List<MyClass> _siblings;
}

They all have the correct properties and what not, I'm just to lazy to type
them.
So what I want to do is display property information with a function that
looks similar to:

public void displayProperties(object o)
{
if(o.GetType().IsValueType || o.GetType() == typeof(string))
Console.writeline(o.ToString());

Type myType = o.GetType();
PropertyInfo[] props = myType.GetProperties(..flags...);
foreach(PropertyInfo p in props)
{
console.writeline(p.Name + ": ");
object anotherO = p.GetValue(o,null);

if(anotherO.GetType().IsValueType || anotherO.GetType() ==
typeof(string))
conole.writeline(anotherO.ToString());
else
displayProperties(anotherO); <-- recursion
}
}

Now I really hacked this up to simplify it, but you get the picture.
My method works pretty well for most objects, but I can't loop through
something that looks like MyClass above. because when I get to the
MyClass.Siblings property it just doesn't know what to do...wait....I don't
know what to do.

If the siblings contains two more elements, I just want to loop through
those and call my same function.
Any ideas how I can do this? Same problem for an ArrayList and the like.
Can I do something like " if(o.IsACollectionOfSomeSort)" "foreach(object z
in 'thecollection')displayProperties(z)"

I hope you can at least understand my problem after all this damn typing....
 
J

Jon Skeet [C# MVP]

INeedADip wrote:

If the siblings contains two more elements, I just want to loop through
those and call my same function.
Any ideas how I can do this? Same problem for an ArrayList and the like.
Can I do something like " if(o.IsACollectionOfSomeSort)" "foreach(object z
in 'thecollection')displayProperties(z)"

I hope you can at least understand my problem after all this damn typing....

Well, you can do:

if (o is IEnumable)
{
foreach (object element in (IEnumerable)o)
{
...
}
}

Note that there are things which implement IEnumerable which you
wouldn't just want to enumerate - and there may be other properties
you're interested in, too.

I suspect you'll find it hard to write a robust version of this which
always does what you want it to, to be honest.

Jon
 
M

Marc Gravell

How about:

IEnumerable e = anotherO as IEnumerable;
if (e != null) {
foreach (object enumItem in e) {
displayProperties(enumItem );
}
}

Haven't tested it, but...?

Also - you should discard null values of anotherO before you call GetType()
or "is"

Marc

anotherO
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top