Imagine the following scenario:
A user passes a string to the application, which represents a .NET-Type, e.g. string
or System.IntPtr
. Assuming, that the application in question has access to the assemblies, in which the given Types are defined, it can create an instance of the given type based on the string.
I have managed to create such an application; the problem is only, that I am not (yet) able to create "complex" or "nested" types, e.g.:
- Generics like
System.Tuple<string, System.Action>
- Arrays of
T
likeint[]
,System.IntPtr[]
, etc... - Pointer of
T
likeint*
,char**
,Namespace.MyStruct*
, etc... - Any (possible) combination of the cases above
My question is: How can I create such nested type instances, when only given the string representation of the type (and of course all required assemblies)?
Do the .NET BCL contain some sort of string --> Type
-parser? Or do I have to use some form of recursive regex-parser and Activator.CreateInstance
?
EDIT №1:
As this question seems to be too broad, I will try to clarify myself:
I am able to create type instances for 'simple' types - I am, however, struggling to create type instances of 'complex' types, e.g.:
Type t1 = typeof(string).Assembly.GetType("System.String");
Type t2 = typeof(string).Assembly.GetType("System.Tuple<System.String, System.Int32>");
object obj1 = Activator.CreateInstance(t1);
object obj2 = Activator.CreateInstance(t2);
obj1
is an instance of string
, but obj2
will fail, as the variable t2
is null
(Meaning, that the second line in the given code was unable to find the 'complex' type).
EDIT №2:
The usage of Type::MakeGenericType(Type[])
is obviously helpful, but how would be the easiest/fastest(?) way to create an instance of a type like this:
IEnumerable<Tuple<int[,], char[][], Dictionary<string, Func<int, int*, byte>>>>
I would have to write some kind of regex-based parser, which iterates recursively over the different sections of the given string....
EDIT №3:
I have discovered System::CodeDom::CodeTypeReference
and I am currently searching for a method to get the type based on a given CodeTypeReference
-instance (which can be created using the type's string representation).
EDIT №4: (sorry for all the edits)
I think I found my solution in this SO post.