views:

2428

answers:

3

I am writing a Clone method using reflection. How do I detect that a property is an indexed property using reflection? For example:

public string[] Items { get; set; }

My method so far:

    public static T Clone<T>(T from, List<string> propertiesToIgnore) where T : new()
    {
        T to = new T();

        Type myType = from.GetType();

        PropertyInfo[] myProperties = myType.GetProperties();

        for (int i = 0; i < myProperties.Length; i++)
        {
            if (myProperties[i].CanWrite && !propertiesToIgnore.Contains(myProperties[i].Name))
            {
                myProperties[i].SetValue(to,myProperties[i].GetValue(from,null),null);
            }
        }

        return to;
    }
+6  A: 
if (PropertyInfo.GetIndexParameters().Length > 0)
{
    // Property is an indexer
}
FlySwat
lol - beat me to it as I was copying the documentation link.
Jeromy Irvine
+2  A: 

What you want is the GetIndexParameters() method. If the array that it returns has more than 0 items, that means it's an indexed property.

See the MSDN documentation for more details.

Jeromy Irvine
+3  A: 

Sorry, but

public string[] Items { get; set; }

is not an indexed property, it's merely of an array type! However the following is:

public string this[int index]
{
    get { ... }
    set { ... }
}