Search code examples
c#objectstructtypeof

Dynamically return fields of variable structure in C#


I can image this problem has a relatively simple solution, which I have however been searching without success so far.

I have a couple of structs to save data within my program, e.g. Data_Type1, Data_Type2, etc. All of these structs have fields, which I would like to access dynamically, e.g. to get an array of strings with the according values and field names. So far, this is done by:

public string[] GetFieldsAsStringFromTypeX(object struct_type)
{
var fields = typeof(Data_TypeX).GetFields();
foreach (var field in fields)
    // do sth
}

Now the question is how to let Data_TypeX be determined dynamically. Something like this

public string[] GetFieldsAsStringFromTypeX(object struct_type)
{
var fields = typeof(struct_type).GetFields();
foreach (var field in fields)
    // do sth
}

does not work, since typeof is expecting a data type.

Thanks in advance!


Solution

  • You can use:

     struct_type.GetType().GetFields();