In C#, I need to be able to create an array of Type objects at run-time based on a comma-delimited list of data types passed in to a 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 like this:
MyFunction("uint, string, string, uint");
and have it generate the array dynamically based on the string passed in. Here was 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'm pretty sure the problem lies here:
listTypes.Add(Type.GetType(t));
Suggestions on why this syntax does not do the trick?
We can create an array of pointers also dynamically using a double pointer. Once we have an array pointers allocated dynamically, we can dynamically allocate memory and for every row like method 2.
Dynamic arrays are resizable and provide random access for their elements. They can be initialized with variable size, and their size can be modified later in the program. Dynamic arrays are allocated on the heap, whereas VLAs are allocated on the stack.
A simple dynamic array can be constructed by allocating an array of fixed-size, typically larger than the number of elements immediately required.
A dynamic array is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern programming languages. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that needs to be specified at allocation.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With