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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With