Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this code compiling?

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?

like image 407
Marcel James Avatar asked Nov 11 '22 23:11

Marcel James


1 Answers

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)

like image 58
Carbine Avatar answered Nov 14 '22 23:11

Carbine