Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a C# array using Reflection and only type info? [duplicate]

I can't figure out how to make this work:

object x = new Int32[7]; Type t = x.GetType();  // now forget about x, and just use t from here.  // attempt1  object y1 = Activator.CreateInstance(t); // fails with exception  // attempt2 object y2 = Array.CreateInstance(t, 7);  // creates an array of type Int32[][] ! wrong 

What's the secret sauce? I can make the second one work if I can get the type of the elements of the array, but I haven't figured that one out either.

like image 951
Mark Lakata Avatar asked Aug 05 '10 21:08

Mark Lakata


People also ask

How do I create a new C project in Visual Studio?

Open Visual Studio, and choose Create a new project in the Start window. In the Create a new project window, select All languages, and then choose C# from the dropdown list. Choose Windows from the All platforms list, and choose Console from the All project types list.

How do I get C in Visual Studio?

1. We need to click on the extension button that displays a sidebar for downloading and installing the C/C++ extension in the visual studio code. In the sidebar, type C Extension. In this image, click on the Install button to install the C/C++ extension.

Can you write C in Visual Studio?

Yes, you very well can learn C using Visual Studio. Visual Studio comes with its own C compiler, which is actually the C++ compiler. Just use the . c file extension to save your source code.


1 Answers

You need Type.GetElementType() to get the non-array type:

object x = new Int32[7]; Type t = x.GetType(); object y = Array.CreateInstance(t.GetElementType(), 7); 

Alternatively, if you can get the type of the element directly, use that:

Type t = typeof(int); object y = Array.CreateInstance(t, 7); 

Basically, Array.CreateInstance needs the element type of the array to create, not the final array type.

like image 120
Jon Skeet Avatar answered Sep 22 '22 01:09

Jon Skeet