I need to get the type of all members present in a class.
public class Order
{
public int OrderID { get; set; }
public int EmployeeID { get; set; }
public string CustomerID { get; set; }
public DateTime OrderDate { get; set; }
public bool Verified { get; set; }
public Order(int orderId, int empId, string custId, DateTime orderDate, bool verify)
{
this.OrderID = orderId;
this.EmployeeID = empId;
this.CustomerID = custId;
this.OrderDate = orderDate;
this.Verified = verify;
}
}
and the value for the class i have added through List
List<dynamic> dy = new List<dynamic>();
dy.Add(new { OrderID = 11, EmployeeID = 5, CustomerID = "ALFKI", OrderDate = new DateTime(2015,01, 10), Verified = true });
dy.Add(new { OrderID = 12, EmployeeID = 4, CustomerID = "CDSAW", OrderDate = new DateTime(2015, 02, 12), Verified = true });
dy.Add(new { OrderID = 13, EmployeeID = 6, CustomerID = "ASDFG", OrderDate = new DateTime(2015, 03, 13), Verified = true });
dy.Add(new { OrderID = 14, EmployeeID = 3, CustomerID = "XSDAF", OrderDate = new DateTime(2015, 04, 14), Verified = false });
dy.Add(new { OrderID = 15, EmployeeID = 2, CustomerID = "MNHSD", OrderDate = new DateTime(2015, 05, 15), Verified = true });
dy.Add(new { OrderID = 16, EmployeeID = 1, CustomerID = "OKJHG", OrderDate = new DateTime(2015, 06, 16), Verified = false });
return dy;
For get the fields types, i tried with the following code.
Type type = dataSource.GetElementType();
Type t = typeof(object);
t = type.GetProperty("OrderDate").PropertyType;
Its throws an null expression error.
Here OrderDate is DateTime object.
Type type = dataSource.GetType();
This line, returns System.object.
When try to get the OrderDate field type.
type.GetProperty(filterString).PropertyType;
returns Null, how to fix this issue.
Online : https://dotnetfiddle.net/zTYJGU
First of all if you want to get all field and property types in specified type you should know some things.
Every property have it's own backing field. For auto generated property
public int MeProperty { get; set; }the backing field will have the name<MeProperty>k__BackingField.Knowing this you should consider extracting
FieldInfoinstead ofPropertyInfo.Another thing is that you're assuming that
GetPropertymethod will extract even hidden (private,protectedetc.. ) members, which is totally wrong. It expects that you specify level of accessability by usingBindingFlagsenumeration.After getting all of that knowledge you can just extract all of the fields instad of properties using :
After that you can enumerate and get field types :
Now you
fieldTypesisIEnumerable<Type>containing every field type specified intypefield.The real problem is that you want to implement auto-mapper which creates your defined type from a dynamic type. For this I would recommend you to use the solution from my answer on this question
EDIT:
Using this code :
You should have the same output as :