views:

139

answers:

4

I have a class with a Items property, which is an IList:

class Stuff {
    IList<OtherStuff> Items;
}

I want to be able to receive a string within a method (I thought of this format originally: Items[0]) and be able to retrieve the first item of the Items list.

I tried this:

object MyMethod(string s, object obj) {
    return obj.GetType().GetProperty(s).GetValue(obj,null);
}

with s being 'Items[0]' but it doesn't work... Also tried parsing the parameter to access only the property 'Items' of the object and then accessing the index (knowing that it is an IList).

None of these approaches worked... Any thoughts?

any thoughts?

+1  A: 

You can access the property and then can you convert it to a list.

T GetListItem<T>(object obj, string property, int index)
{
    return (obj.GetType().GetProperty(property).GetValue(obj, null) as IList<T>)[index];
}

Working example for your sample code:

OtherStuff item = GetListItem<OtherStuff>(obj, "Items", 0);
BlueCode
Actually, this was my second attempt I tried to show above, but obj.GetType().GetProperty(property) is returning null for me. Shouldn't it? If so, this means the problem is somewhere else, and I have to take a closer look here.
Rodrigo Gama
A: 

If you want to test an object to see if it has a numeric indexer, without regard to whether it is an IList, and then invoke the indexer via reflection, you can try out this method.

It returns true if the object has an indexer, and populates value with the value of the 0th index as well.

public static bool TryGetFirstIndexWithReflection(object o, out object value)
{
    value = null;

    // find an indexer taking only an integer...
    var property = o.GetType().GetProperty("Item", new Type[] { typeof(int) });

    // if the property exists, retrieve the value...
    if (property != null)
    {
        value = property.GetValue(list, new object[] { 0 });
        return true;
    }

    return false;
}

Note that this example makes no attempt to gracefully handle exceptions, such as IndexOutOfRangeException. That's up to you to add if you find it relevant.

kbrimington
A: 

You should try this :

object GetFirstItemByReflection(object obj) {
    return obj.GetType().GetMethod("get_Item").Invoke(obj, new object[] { 0 } );
}

with the appropriate checks.

"get_Item" is the "generated" method used when you access items by index in a collection. When you get it's MethodInfo, you invoke it on your collection, passing it the "0" parameter, to get the first item.

mathieu
A: 

As Chris have posted the answer as a comment, I'm gonna post it hera as an answer:

Items was not a property, so my approaches wouldn't work. It should be, so I transformed it into a property and now it is working smoothly. Thanks Chris...

Rodrigo Gama