Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert c# by-reference type to the matching non-by-reference type

Tags:

c#

reflection

I examine the parameters of a C# method using reflection. The method has some out parameters and for these I get back types, which have IsByRef=true. For example if the parameter is declared as "out string xxx", the parameter has type System.String&. Is there a way to convert System.String& back to System.String? The solution should of course not only work for System.String but for any type.

like image 503
Achim Avatar asked Sep 21 '09 12:09

Achim


1 Answers

Use Type.GetElementType().

Demo:

using System;
using System.Reflection;

class Test
{
    public void Foo(ref string x)
    {
    }

    static void Main()
    {
        MethodInfo method = typeof(Test).GetMethod("Foo");
        Type stringByRef = method.GetParameters()[0].ParameterType;
        Console.WriteLine(stringByRef);
        Type normalString = stringByRef.GetElementType();
        Console.WriteLine(normalString);        
    }
}
like image 164
Jon Skeet Avatar answered Oct 19 '22 11:10

Jon Skeet