Chris Cunning
Chris Cunning

Reputation: 13

Generics typeof <T> with Activator

I currently have to use a large class that has a common property name. The details within the sub class are the same (I am unable to change the class). Instead of adding the Amount class over again to different sections I would like to use generics and reflection to instantiate it.

I have the following code:

var amountProperty = value.GetType().GetProperty("Amount");
if (amountProperty != null && amountProperty.PropertyType.IsArray)
{
    Type amountTypeArray = amountProperty.PropertyType;
    Type amountType = amountProperty.PropertyType.GetElementType();

    var amountValue = amountProperty.GetValue(value);
    if (amountValue == null)
    {
        amountValue = Activator.CreateInstance(amountTypeArray);
    }
    else
    {
        amountValue = IncrementArray<amountType>(amountValue);
    }
}

The 3rd last line amountValue = IncrementArray<amountType>(amountValue); has an error on amountType. If I put it in typeof(amountValue) also doesn't work. The incrementArray method is:

protected T[] IncrementArray<T>(T[] arrayIncrement)
{
    var sectionCopy = arrayIncrement;
    Array.Resize<T>(ref sectionCopy, arrayIncrement.Length + 1);
    return sectionCopy;
}

I am probably just missing a real simple solution.

Upvotes: 0

Views: 79

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You need to use Reflection to call IncrementArray<T> method.

First get the MethodInfo then use MakeGenericMethod

// Assuming incrementMethod is the MethodInfo of IncrementArray<T>
incrementMethod.MakeGenericMethod(amountType).Invoke(amountValue);

Upvotes: 1

Related Questions