Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instance with type object during runtime [duplicate]

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

like image 656
Oumdaa Avatar asked Nov 06 '12 15:11

Oumdaa


1 Answers

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

like image 134
Knaģis Avatar answered Oct 02 '22 00:10

Knaģis