[Solved] C# System.Double& to System.Double


The ampersand & probably comes from the CLR name of the type. It indicates that it is a ByRef version of the type. Did you get the Type with reflection from a method parameter decorated with the ref or out keyword?

Example:

var t1 = typeof(double);
Console.WriteLine(t1);        // "System.Double"
var t2 = t1.MakeByRefType();
Console.WriteLine(t2);        // "System.Double&"
var t3 = t2.GetElementType();
Console.WriteLine(t3);        // "System.Double"

Console.WriteLine(t1 == t3);  // "True"

For an example with the ref keyword, suppose you have a method (inside a type Program) that looks like this:

public static bool TestMethod(ref double d)
{
  return true;
}

Then you can do:

var t4 = typeof(Program).GetMethod("TestMethod").GetParameters()[0].ParameterType;
Console.WriteLine(t4);        // "System.Double&"

Again, you can remove the & with GetElementType().

The same with the array type, it can also be ByRef or not.


Additions after edits:

Instead of e.g. Type.GetType("System.String[]") I strongly suggest you use typeof(string[]). It is much safer to use the C# keyword typeof.

If you want to get rid of any “trailing ampersand”, that is if you want to remove “ByRef” when present, you can say:

Type t = param.ParameterType;
if (t.IsByRef)
    t = t.GetElementType();

Finally, the reason why you get a run-time exception seems to be a misspelling of Dobule.
Wouldn’t have happened with typeof(double) (spelling would be checked at compile-time).

And it is much, much easier to say:

return " ";

instead of your:

return Activator.CreateInstance(Type.GetType("System.String"), new object[] { new char[] { ' ' } });

and to say:

return new double[10];

instead of your:

return Activator.CreateInstance(Type.GetType("System.Double[]"), new object[] { 10 }); // spelling error fixed

Why make everything so indirect?

4

solved C# System.Double& to System.Double