I’ve seen a lot of questions asked about instantiating classes from a string but have been unable to find any information on creating a structure the same way.
I have a class which contains a structure like so:
Public Structure callDetails
Public GUID As Guid
Public ringTime as Date
Public CBN As String
etc.
All I really want to do is get the field names from the structure. I don’t care to manipulate the data in the fields.
So far I can get pretty close with this.
callDetails callTableDef= new callDetails();
Type tableType = callTableDef.GetType();
object tableStruct = (object)Activator.CreateInstance(tableType);
System.Reflection.FieldInfo[] fields = tableType.GetFields();
foreach (System.Reflection.FieldInfo field in fields)
Debug.WriteLine(field.Name + " = " + field.GetValue(tableStruct));
However, I still need to create an instance of the structure with the actual name. I want to be able to pass in a string like this:
Type tableType = System.Type.GetType("callDetails");
When I do that I get an ArgumentNullException from Activator.CreateInstance()
Isn’t getType supposed to look up the value passed to it as a string and return the type?
I’m new to C# having programmed mostly in Java until this project.
You must qualify the type name with its namespace:
If it’s in a different assembly, you need the assembly qualified name. Details can by found on MSDN. With just the type name as you have, it won’t be able to resolve and will return
null, hence your argument null exception.