BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Reflection
.NET 1.1+

Reflecting ref and out Parameter Information

Methods and their parameters can be examined using reflection to obtain detailed information about their use. When reflecting method parameters, it may be necessary to determine if they are reference or output parameters.

Obtaining the Underlying Parameter Type

When you reflect output and reference parameters, the data type for each parameter is different than what you might expect. The reflected type will not be that defined in the method's signature. It will actually be a pointer for that type. For example, an output parameter of the int type will be seen as a integer pointer (int&).

If you need to find the data type as defined in the method, you can call the GetElementType method against the ParameterType value. You should only do this for output and reference parameters.

The final example demonstrates this. The code outputs each parameter name; whether the parameters are standard, output or reference parameters; and the data type in each case.

static void Main()
{
    Type type = typeof(TestClass);
    MethodInfo info = type.GetMethod("TestMethod");
    ParameterInfo[] parameters = info.GetParameters();

    foreach (ParameterInfo pi in parameters)
    {
        Console.WriteLine(pi.Name);
        Console.WriteLine(GetRefValueType(pi));
        Console.WriteLine(GetPassedType(pi));
        Console.WriteLine();
    }
}

static string GetRefValueType(ParameterInfo pi)
{
    if (pi.IsOut)
        return "Output Parameter";
    else if (pi.ParameterType.IsByRef)
        return "Reference Parameter";
    else
        return "Standard Parameter";
}

static Type GetPassedType(ParameterInfo pi)
{
    Type parameterType = pi.ParameterType;

    if (parameterType.IsByRef)
        return parameterType.GetElementType();
    else
        return parameterType;
}

/* OUTPUT

stdParam
Standard Parameter
System.Int32

outParam
Output Parameter
System.Int32

refParam
Reference Parameter
System.Int32

*/
2 January 2014