How to dereference ParameterType for parameters passed by ref

410 views Asked by At

I have the following code-snippet (it is just an example to point out my problem to which I am finding a solution):

public class Test
{
    public enum myEnum
    {
        myEnum1,
        myEnum2,
    }

    public static void Refer(out int a, int b, out int[] intArray, bool[] boolArray, myEnum enumerated1, out myEnum enumerated2)
    {
        a = b;
        intArray = new int[] { 1, 2, 3 };
        enumerated2 = enumerated1;
    }

    static void Main()
    {
        MethodInfo method = typeof(Test).GetMethod("Refer");
        ParameterInfo[] parameters = method.GetParameters();
        foreach (ParameterInfo parameter in parameters)
        {
            Console.WriteLine("Type of {0} is {1}", parameter.Name, parameter.ParameterType.Name);

            Console.WriteLine("{0} is passed by ref   : {1}", parameter.Name, parameter.ParameterType.IsByRef ? "Yes" : "No");
            Console.WriteLine("{0} is a primitive type: {1}", parameter.Name, parameter.ParameterType.IsPrimitive ? "Yes" : "No");
            Console.WriteLine("{0} is an array        : {1}", parameter.Name, parameter.ParameterType.IsArray ? "Yes" : "No");
            Console.WriteLine("{0} is an enumeration  : {1}", parameter.Name, parameter.ParameterType.IsEnum ? "Yes" : "No");
            Console.WriteLine();
        }
        Console.ReadKey();
    }
}

Where I get stuck is in the case of the reference parameters. In the output I can see when a parameter is passed by reference, but what I do not see is whether the type of the parameter the reference points to is e.g. an array of primitive type.

I would like to have information regarding the type of what the reference is referencing to. In order to do that, I am assuming I somehow need to dereference the parameter, but I cannot figure out how to do this (e.g. in this example, I would like to see that parameter "int a" IsPrimitive (after dereferencing).

So the question is, how to dereference the reference?

2

There are 2 answers

1
user5090812 On BEST ANSWER

If a type is byref, use GetElementType() on it to get the underlying non-ref type.

0
György Kőszeg On
static void Main()
{
    MethodInfo method = typeof(Test).GetMethod("Refer");
    ParameterInfo[] parameters = method.GetParameters();
    foreach (ParameterInfo parameter in parameters)
    {
        Type paramType = parameter.ParameterType;
        Console.WriteLine("Type of {0} is {1}", parameter.Name, paramType.Name);

        Console.WriteLine("{0} is passed by ref   : {1}", parameter.Name, paramType.IsByRef ? "Yes" : "No");

        // extracting element type (works for arrays, too)
        if (paramType.IsByRef)
            paramType = paramType.GetElementType();

        // this will print Yes for a ref int
        Console.WriteLine("{0} is a primitive type: {1}", parameter.Name, paramType.IsPrimitive ? "Yes" : "No");

        // ...
    }
}