Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create an array and set the elements

This can create an array dynamically:

Assembly asm = object.GetType().Assembly;
string sTypeName = "Company.Namespace.ClassName";
object arrayWithSize1 = Activator.CreateInstance( asm.GetType(sTypeName), 1 );

But how does set the first element of array which is created above?

like image 825
uzay95 Avatar asked Jan 26 '12 17:01

uzay95


People also ask

How do you dynamically add elements to an array?

There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.

Can we create a dynamic array?

A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required.

What is dynamic array How is it created?

A dynamic array is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern programming languages. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that needs to be specified at allocation.

How do you create an array of objects dynamically in Java?

Creating an Array Of Objects In Java – An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.


1 Answers

You can use Array.SetValue:

 // How are you going to create this? Activator.CreateInstance?
 object instance = ...

 // Create one-dimensional array of length 1.
 Array arrayWithSize1  = Array.CreateInstance(asm.GetType(sTypeName), 1);

 // Set first (only) element of the array to the value of instance.
 arrayWithSize1.SetValue(instance, 0);
like image 106
Ani Avatar answered Sep 29 '22 06:09

Ani