Creating an instance with an object of type at run time

I have the following code

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

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

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

I need to create anagrammatically variables of type t

+4
source share
2 answers

The first step is to extract the actual type you want to create. Most likely, the type name is stored in the database as a string. Therefore you call

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

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

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

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

 var i = (IFormattable)obj; 

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

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

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

+16
source

Knaģis already provided the corresponding answer, but I wanted to indicate that this line of code is incorrect:

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

This will always return Type , not string , int , etc. This is because the DataType is equal to Type . Use this instead:

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

In addition, you use a naming convention for the generic type. Although this confuses the first reading a bit, nothing happens to it. Just keep in mind that there is a difference between a generic type and a variable. For example, enter the code in your question, you could not 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 will result in a compile-time error.

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

+2
source

Source: https://habr.com/ru/post/1444398/


All Articles