views:

817

answers:

2

Hi. I'm trying to validate that a parameter is both an out parameter and extends an interface (ICollection). The reflection api doesn't seem to want to give me the "real" type of the parameter, only the one with an "&" at the end which will not evaluate correctly in an IsAssignableFrom statement. I've written some c# code that works but it seems like there should be a better way to do this.

bool isCachedArg(ParameterInfo pInfo)
{    
    if (!pInfo.IsOut)
        return false;

    string typeName = pInfo.ParameterType.FullName;
    string nameNoAmpersand = typeName.Substring(0, typeName.Length - 1);
    Type realType = Type.GetType(nameNoAmpersand);

    if (!typeof(ICollection).IsAssignableFrom(realType))
        return false;

    return true;
}

Is there a way to get realType without reloading the Type from its string name? I'm still on .NET 2.1.

Thanks, Randy

+3  A: 

Is pInfo.ParameterType not the type you are looking for ?

According to docs, the ParamterType property of the PropertyInfo class is: "The Type object that represents the Type of this parameter."

Also, the following code gives the expected output:

    Type t = typeof (X);
    var mi = t.GetMethod("Method");
    var parameters = mi.GetParameters();
    foreach(Type parameterType in parameters.Select(pi => pi.ParameterType))
            Console.WriteLine(parameterType.IsByRef ? parameterType.GetElementType() : parameterType);

Edit: As John Skeet points out, if the parameter is by ref; you should use GetElementType to get the correct type. I updated the code sample.

driis
+7  A: 

An out parameter is "by ref" - so you'll find pInfo.ParameterType.IsByRef returns true. To get the underlying not-by-ref type, call GetElementType():

Type realType = pInfo.ParameterType.GetElementType();

(You should only do that if it is by ref, of course.)

Jon Skeet
+1 "An out parameter is 'by ref'".
Andrew Hare
You are absolutely right, I missed the by ref part in my answer :-) +1.
driis
Works great. Thank you!
randy909
if i find the parameter type to be say bool or int or whatever, how do i create an instance of that type, give it a value and then invoke the method or constructor with an array or arguments?
towps
pInfo.ParameterType.GetElementType(); returns null for my boolean parameter. Type.GetType(pi.ParameterType.FullName) gets what I want but now how do I actually make a boolean and give it a value so I can give it to a method or constructor?
towps
@towps Yes, it would return null for a simple boolean parameter - that doesn't have an element type. Your question is a bit confused, and sounds like it deserves a full question rather than just a comment to an answer in a different question.
Jon Skeet