Dynamically create an array of type in C #

In C #, I need to be able to create an array of Type objects at runtime based on a list of data separated by commas, data types passed to the function as a string. Basically, here is what I am trying to accomplish:

// create array of types Type[] paramTypes = { typeof(uint), typeof(string), typeof(string), typeof(uint) }; 

But I need to be able to call my function as follows:

 MyFunction("uint, string, string, uint"); 

and make it generate an array dynamically based on the passed string. Here is my first attempt:

 void MyFunction(string dataTypes) { //out or in parameters of your function. char[] charSeparators = new char[] {',', ' '}; string[] types = dataTypes.Split(charSeparators, stringSplitOptions.RemoveEmptyEntries); // create a list of data types for each argument List<Type> listTypes = new List<Type>(); foreach (string t in types) { listTypes.Add(Type.GetType(t)); } // convert the list to an array Type [] paramTypes = listTypes.ToArray<Type>(); } 

This code simply creates an array of null objects of type System.Type. I am sure the problem is here:

 listTypes.Add(Type.GetType(t)); 

Suggestions on why this syntax doesn't do the trick?

+6
arraylist arrays list c # runtime
source share
4 answers

The problem is that in .NET there are no uint and string types. These are C # type aliases for the actual System.UInt32 and System.String . Therefore, you should call your function as follows:

 MyFunction("System.UInt32, System.String, System.String, System.UInt32"); 
+4
source share

Go to System.String , System.Int32 instead of string and int .

"string" is simply an abbreviation for System.String. Type.GetType will not accept abbreviated type notations.

+5
source share

Use the fully qualified name for each type, including the namespace. For example:

 class Program { static void Main(string[] args) { var dataTypes = "System.UInt32, System.String, System.String, System.UInt32"; //out or in parameters of your function. char[] charSeparators = new char[] { ',', ' ' }; string[] types = dataTypes.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); // create a list of data types for each argument List<Type> listTypes = new List<Type>(); foreach (string t in types) { listTypes.Add(Type.GetType(t)); } // convert the list to an array Type[] paramTypes = listTypes.ToArray<Type>(); } } 
+3
source share

This does not work because uint , string , etc. are not official .net type names. These are C # aliases for System.UInt32 , System.String , etc. You will need to use .net type names if you want to dynamically create types.

+1
source share

All Articles