TransWikia.com

How to initialize correctly an array with Array.CreateInstance() method

Stack Overflow Asked by DonMiguelSan on January 26, 2021

I am working with a project and I got stucked, I want to create an array of a class, this class contains two int fields, I want to create an instance with Array.CreateInstance(), this method creates correctly an array with the correct length but instead of giving access to the int variables, the array is initialize as an array of null.

This is a simulation, the name of the class ProcessFaults is read during runtime with the reflection.

public class ProcessFaults
{

    public int _class;

    public int _group;

    public ProcessFaults()
    {

    }
}

class Program
{ 
    static void Main(string[] args)
    {
        object activatorTest = Activator.CreateInstance(typeof(Container));

       
        FieldInfo arrayFieldInfoInsideClass = Type.GetType("Testing_Reflection.Container").GetField("_dataProcessFaults", BindingFlags.Instance | BindingFlags.Public);
        Type arrayTypeInsideClass = arrayFieldInfoInsideClass.FieldType;

        FieldInfo elementClassInsideArray = arrayTypeInsideClass.GetElementType().GetField("_class", BindingFlags.Instance | BindingFlags.Public);


        Array a = Array.CreateInstance(arrayTypeInsideClass, 10);
}
}

that Produces following Output:

enter image description here

  • Is there any form to initialize correctly the array?
  • Is there any form to write directly to the variable _class and _group?

Regards!

One Answer

The elements of an array are always null when it is first instantiated if those types are reference types.

var x =  new ProcessFaults[10];
Console.WriteLine(x[0] == null); // writes "True"

In your case, you simply iterate over the array and use Activator.CreateInstance to instantiate a new instance and SetValue to set it to the Array

for(var i=0;i<a.Length;i++)
    a.SetValue(Activator.CreateInstance(arrayTypeInsideClass),i);

Live example: https://dotnetfiddle.net/65Iji8

Correct answer by Jamiec on January 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP