Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Reflection - How to get "real" type from out ParameterInfo

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

like image 316
randy909 Avatar asked Apr 10 '09 17:04

randy909


1 Answers

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. This applies for ref parameters too.)

like image 111
Jon Skeet Avatar answered Oct 01 '22 15:10

Jon Skeet