8

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?

bluish
  • 26,356
  • 27
  • 122
  • 180
uzay95
  • 16,052
  • 31
  • 116
  • 182

2 Answers2

14

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);
Ani
  • 111,048
  • 26
  • 262
  • 307
7

You can just use the dynamic keyword to make the code more readable than reflection calls:

var arrayType = typeof(int);
dynamic array = Array.CreateInstance(arrayType, 1);
array[0] = 123;
millimoose
  • 39,073
  • 9
  • 82
  • 134