Marcel James
Marcel James

Reputation: 874

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?

Upvotes: 5

Views: 115

Answers (2)

Carbine
Carbine

Reputation: 7903

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)

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

The default statement doesn't work with System.Type.

That being said, it seems more appropriate to leave that out, and use DBNull directly:

linha[itemField.Name] = itemField.GetValue(recordOnEnumerable) ?? DBNull.Value;

If the value is null, setting the result to null (which, in a DataRow, is DBNull.Value) seems appropriate.

Upvotes: 0

Related Questions