Following on from another question on Stack Overflow by a different user, I thought I would try the code and see if I could improve it.
I would like clarification on a number of things:
- I am assuming that getting property information via reflection is costly? Correct?
- With
PropertyInfo.SetValue(Object, Object, Object[])
what is the last parameter for? Am I safe passing in null? - Is there any other improvements that are obvious in my code?
The whole point is a learning exercise to see if I can create something like Dapper (which is very nice) but without the nasty looking (because i have no idea) IL emit stuff. With this is mind, I tried to implement some sort of caching with the assumtion that reflection is bad for perfomance.
The Code
private T CreateItemFromRow<T>(SqlDataReader row, List<PropertyInfo> properties, Dictionary<String, Int32> schema) where T : new()
{
T item = new T();
if (schema != null && properties != null && row != null)
{
foreach (var property in properties)
{
if (schema.ContainsKey(property.Name))
{
// is this ok?
if (row[0].GetType() == property.PropertyType)
{
property.SetValue(item, row[schema[property.Name]], null);
}
else
{
property.SetValue(item, Convert.ChangeType(row[schema[property.Name]], property.PropertyType), null);
}
}
}
}
return item;
}
The properties is passed in from this method:
private List<PropertyInfo> GetPropertyInformation<T>()
{
List<PropertyInfo> properties;
Type _T = typeof(T);
if (!PropertyCache.ContainsKey(_T))
{
properties = _T.GetProperties().ToList();
PropertyCache.Add(_T, properties);
}
else
{
properties = PropertyCache[_T];
}
return properties;
}
And this is the declaration of PropertyCache
private static Dictionary<Type, List<PropertyInfo>> PropertyCache { get; set; }