I’ve got an object which I create out of an entity(T) using reflection. The object is my implementation of a table. It holds a list of columns, and I extract their properties from the entity using reflection :
public class Generic_Table<T> : Table
{
...// in ctor
type = this.GetType().GetGenericArguments()[0]; // type of T
BuildColumns(type);
private void BuildColumns(Type type)
{
PropertyInfo[] properties = type.GetProperties();
Columns = new KeyValuePair<string, Type>[properties.Count()];
int i = 0;
foreach (PropertyInfo property in properties)
{
Columns[i++] = new KeyValuePair<string, Type>(property.Name, property.PropertyType);
}
}
I’m looking for a way to cast the PropertyType value as a nullable type, so that the Type value in columns would be int? if, for example, some property has int for its
PropertyType value.
This will do what you need:
The
MakeGenericTypemethod accepts a params array of the generic type arguments. See the documentation for more details:Also, this article has a good example of something similar to what you’re doing here: