1

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!

3
  • Do var arr = (ProcessTypes[])a; then initialise arr[] in a loop as you would a normal array. Commented Aug 11, 2020 at 7:54
  • the array is length 10 of the class ProcessFaults @TheGeneral. Commented Aug 11, 2020 at 8:00
  • 1
    @MatthewWatson the explicit cast would work, i think i did not mention that in run time i do not know the explicit name of the class ProcessFaults, ProcessFaults is read with reflection Commented Aug 11, 2020 at 8:01

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.