4

Say I have this C# class

public class MyClass {
    int a;
    int[] b = new int[6];
}

Now say I discover this class using reflection and while looking at the fields I find that one of them is of type Array (ie: b)

foreach( FieldInfo fieldinfo in classType.GetFields() )
{
    if( fieldInfo.FieldType.IsArray )
    {
        int arraySize = ?;
        ...
    }
}

I know it's not guaranteed that the array has a field initializer that creates the array but if it does I would like to know the size of the array created by the field initializer.

Is there a way to call the field initializer ?

If there was I would do something like this:

Array initValue = call field initializer() as Array;
int arraySize = initValue.Length;

The only was I found is to create an instance of the whole class but I would rather not do it like this as it's overkill...

Éric
  • 181
  • 2
  • 15

2 Answers2

3

Well, you can't.

The following code:

public class Test
{
    public int[] test = new int[5];

    public Test()
    {
        Console.Read();
    }
}

will be compiled as:

public class Program
{
    public int[] test;

    public Program()
    {
        // Fields initializers are inserted at the beginning
        // of the class constructor
        this.test = new int[5];

        // Calling base constructor
        base.ctor();

        // Executing derived class constructor instructions
        Console.Read();
    }
}

So, until you create an instance of the type, there is no way to know about the array size.

ken2k
  • 48,145
  • 10
  • 116
  • 176
  • Well not quite because they say in the documentation that field initializers are executed before the constructor is called. – Éric Feb 06 '13 at 16:12
  • @user1857628 I'm taking about **instance** fields (not static), and the case you provide doesn't imply inheritance. The field initializer is executed before the **base** constructor, not the constructor of the most derived class. I added the call to the base constructor in the example to make it more clear. – ken2k Feb 06 '13 at 16:21
0

I dont think you have an option but to create an instance of the class as it doesnt exist until you do that.

CathalMF
  • 9,705
  • 6
  • 70
  • 106
  • He could root about the method and figure it out using some form of IL reflection, which in my opinion is 100x more overkill. But it IS technically an option. – Aron Feb 06 '13 at 16:44