I'm writing a method to generate a DataTable taking as datasource a generic IEnumerable. I am trying to set a default value on the field if theres no value, with the code below:
private void createTable<T>(IEnumerable<T> MyCollection, DataTable tabela)
{
Type tipo = typeof(T);
foreach (var item in tipo.GetFields() )
{
tabela.Columns.Add(new DataColumn(item.Name, item.FieldType));
}
foreach (Pessoa recordOnEnumerable in ListaPessoa.listaPessoas)
{
DataRow linha = tabela.NewRow();
foreach (FieldInfo itemField in tipo.GetFields())
{
Type typeAux = itemField.GetType();
linha[itemField.Name] =
itemField.GetValue(recordOnEnumerable) ?? default(typeAux);
}
}
}
It's throwing this error:
The type or namespace name 'typeAux', could not be found (are you missing a using directive or an assembly reference?)
Why? Shouldn't the function "Default(Type)" return a default value for that type?
How about returning null for reference types and Activator.CreateInstance for value types
public static object GetDefault(Type type)
{
if(type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
Reference: Programmatic equivalent of default(Type)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With