5

I have the following code

//^process a aquery and return DataTable
DataTable d t= dbConnect.ProcessQuery(strquery);
Type t = dt.Columns[0].DataType.GetType();

How to create objects of type t that will receive the dt[0][..] ?

I know that dt.Rows[][] will be of type t

I need to create anagrammatically variables of type t

nawfal
  • 70,104
  • 56
  • 326
  • 368
Oumdaa
  • 677
  • 6
  • 14

2 Answers2

17

First step is to retrieve the actual type you want to create. Most probably, the name of the type is stored in the database as a String. So you call

var typeName = "System.Int32";
var type = System.Type.GetType(typeName);

Now that you have the actual type you want to instantiate, call

var obj = System.Activator.CreateInstance(type);

In most cases you would have a common base interface for all types that you would ever use in each scenario:

var i = (IFormattable)obj;

Now you can call the methods on the interface and they will be executed on the actual type.

Console.WriteLine(i.ToString("0", System.Globalization.CultureInfo.InvariantCulture));

Documentation: http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

Stefanvds
  • 5,868
  • 5
  • 48
  • 72
Knaģis
  • 20,827
  • 7
  • 66
  • 80
2

Knaģis already provided the appropriate answer, but I wanted to point out that this line of code is incorrect:

Type T =dt.Columns[0].DataType.GetType();

This will always return Type, not string, int, etc. That's because the Type of DataType is Type. Use this instead:

Type T =dt.Columns[0].DataType;

Also, you are using the naming convention for a generic type. While it's a bit confusing on the first read, there's nothing "wrong" with it. Just be aware that there's a difference between a generic type and a variable. For example, give the code in your question, you would not be able to use this code:

var x = new List<T>;

In the context of your code, T is a variable, not a generic type, so the above would cause a compile-time error.

See this question for more information:
Generics in C#, using type of a variable as parameter

Community
  • 1
  • 1
JDB
  • 25,172
  • 5
  • 72
  • 123