views:

94

answers:

2

A generic method is defined as follows:

    private static T GetComparisonObject<T>(ComparisonAttribute attribute, object objectToParse)
    {

        // Perform a some action
        return (T)resultObject;
    }

The method is invoked as follows:

var srcObjectToCompare = GetComparisonObject<DynamicType>(attributeToCompare, srcObject);

The type for which the method needs to be invoked is configured in the config file as:

<add attributename ="Count" attributetype ="MemberInformation" attributeparam ="Count" type="System.Int32" comparertype="ditCreditEMGTestAutomationDifferenceEngine.Comparers.TypeComparer, ditCreditEMGTestAutomationDifferenceEngine.dll"  />

The token that is passed in <> for the generic methods has to be the type for which the method is being invoked. From the type key configuration in the XML, an instance of Type represnting the type can be created{i.e. Type.GetType("System.Int32")}, but how can the Type Definition be generated which can then be passed to the the Generic method?

Hope am not missing something elementary here!! :-O

Thanks in advance.

+1  A: 

You have to use reflection:

Type runtimeType = //get the type
MethodInfo method = typeof(MyClass).GetMethod("GetComparisonObject").MakeGenericMethod(runtimeType);
object returnValue = method.Invoke(null, new object[] { attribute, parseObject });

However, it's important to note that this approach throws out the whole value of generics. As you can see above, the result of the method invocation is an object, and since we don't know the type at compile time, we can't get any type checking. If you don't know the type at compile time, there's no point in using a generic method.

Rex M
+3  A: 

Call generic method using reflection

MethodInfo method = typeof(YourClass).GetMethod("GetComparisonObject");
MethodInfo generic = method.MakeGenericMethod(GenericArgumentType);
Object retVal = generic.Invoke(this, new object[] { attribute, parseObject });
this. __curious_geek
Thanks guys! As you might have noticed the return type of the method is "generic", so invoking this method using Reflection to get back "object" kinda beats the purpose of the given method being generic. Will try some other approach for typesafety, but this does answer my question.
Codex