Question

I have Type variable t with value representing reference e.g. System.Double& or System.Double[]&, ... Now I would like to create an instance of object with type System.Double or System.Double[], ...

Question edit:

        Type t = param.ParameterType;
        if (t == Type.GetType("System.String&"))
            return Activator.CreateInstance(Type.GetType("System.String"), new object[] { new char[] { ' ' } });
        if (t == Type.GetType("System.Double[]&"))
            return Activator.CreateInstance(Type.GetType("System.Dobule[]"), new object[] { 10 }); // throw Error !!!!
        else
            return Activator.CreateInstance(t.GetElementType());

Edit 2: I would like to implement something like this:

Type t = param.ParameterType;
if t is a reference to an array of any dimensions -> create its instance
if t is a ref to string -> create its instance
if t is a ref to any other data types -> create its instance
Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top