1

I would like to create a DataTable but I don't know the types of columns at compile time. Therefore, I would like the columns types to be decided at run-time.

WHAT I'VE TRIED:

First, I get some data from Excel:

Type tempCheck = (dynamic)(xlRange.Cells[1, currentColumnsCount] as Excel.Range).Value2.GetType();

Then I try to use the type to create a column.

myDataTable.Columns.Add(columnName, typeof(tempCheck.GetType());

I get the error:

The type or namespace name 'tempCheck' could not be found (are you missing a using directive or an assembly reference?)

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
LLaP
  • 2,528
  • 4
  • 22
  • 34

1 Answers1

4

tempCheck is already a type, so you don't need the typeof:

myDataTable.Columns.Add(columnName, tempCheck);

typeof is an operator that is used to get an instance of System.Type from a type name, and this is done at compile time.

The error "The type or namespace name 'tempCheck' could not be found" is coming because since typeof is looking for a compile-time type, it's literally looking for a type called tempCheck, like a class or delegate, etc.

vcsjones
  • 138,677
  • 31
  • 291
  • 286