Home > database >  Iterate over dynamic object fields and get field data type
Iterate over dynamic object fields and get field data type

Time:06-12

I have object in dynamic type, and index variable in Int data type. Is it possible to get type of field of dynamic object in given index?

Pseudocode:

dynamic dynamicObject = ...
var type = GetType(dynamicObject.Fields[index]); // Int, String or another.

For instance

dynamic dynamicObject = new
{
   Name = "Bla",     
   Age = 2,
   Surname = "Bla Bla"
};
int index = 2;

And I want to get System.String

CodePudding user response:

use reflection. it will work just as well if you use object type instead of dynamic, or allow type inference with var:

var dynamicObject = new
{
   Name = "Bla",     
   Age = 2,
   Surname = "Bla Bla"
};
int index = 2;
System.Reflection.PropertyInfo[] allProps = dynamicObject.GetType().GetProperties();
System.Reflection.PropertyInfo prop = allProps[index];
Type type = prop.PropertyType;
  • Related