Dynamically create an array of Type in C#
Pass in System.String
, System.Int32
instead of string
and int
.
"string" is just shorthand for System.String. Type.GetType
will not accept shorthand notation for types.
The problem is that there are no uint
and string
types in .NET. Those are C# type aliases to the actual System.UInt32 and System.String types. So you should call your function like this:
MyFunction("System.UInt32, System.String, System.String, System.UInt32");
Use the full name for each type, including namespace. Like so:
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>();
}
}