Ali Soltani
Ali Soltani

Reputation: 9946

Cast FieldInfo to list in C#

I have string array like this:

namespace DynamicCore
    {
        public class DynamicCode
        {
            List<Variable> variableList = new List<Variable>();
            public DynamicCode()
            {
                Variable Variable = new Variable();                    
                Variable.ID = "Variable_26545789";
                Variable.Type = 1;

                variableList.Add(Variable);

                Variable = new Variable();
                Variable.ID = "Variable_vdvd3679";
                Variable.Type = 2;

                variableList.Add(Variable);
            }
        }
    }

I compiled this array and store it to memory. I get variableList by this code:

string name = "DynamicCore.DynamicCode";
Type type = results.CompiledAssembly.GetType(name, true);
object instance = Activator.CreateInstance(type);    
FieldInfo filed = type.GetField("variableList", 
                                 BindingFlags.Instance | 
                                 BindingFlags.NonPublic);

I try to cast filed(variableList) to List<Variable> like this:

List<Variable> Variables = (List<Variable>)filed;

But I got this error:

Cannot convert type 'System.Reflection.FieldInfo' to 'System.Collections.Generic.List<Variable>'    

It would be very helpful if someone could explain solution for this problem.

Upvotes: 3

Views: 2836

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43946

filed is only the FieldInfo, an object that describes the field, it's not the value of the field.

To get the value of the field, use GetValue like this:

var list = (List<Variable>)filed.GetValue(instance);

This returns the value of the field variableList of the instance instance.

Upvotes: 3

Martin Mulder
Martin Mulder

Reputation: 12934

Your variable filed is filled with metadata about your field Variable. Using this metadata you can find out in which class it is located, if it is private, etc. etc.

You want something else. You want to retrieve the value of the field use it. You need one extra step:

object theActualValue = filed.GetValue(instance);

You can use this value to cast to your list:

List<Variable> Variables = (List<Variable>)theActualValue;

My suggestion is to rename so stuff to make it more readable. Your code could look like this:

FieldInfo field = type.GetField("variableList", 
                             BindingFlags.Instance | 
                             BindingFlags.NonPublic);
List<Variable> variables = (List<Variable>)field.GetValue(instance);

Upvotes: 4

Related Questions