views:

108

answers:

3

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.

+4  A: 

You must qualify the type name with its namespace:

Type tableType = System.Type.GetType("mynamespace.callDetails");

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.

David M
+1  A: 

If the struct or class is accessible, meaning you have a reference to it, it's better to use GetType, because that takes the struct/class instead of a string. This means it'll fail at compile time when there's an error, and also gives you better refactor possibilities

Type tableType = GetType(callDetails)

In C#:

Type tableType = typeof(callDetails);
Sander Rijken
A: 

Thanks David,

That MSDN reference was exactly what I needed. I tried qualifying it as many ways as I knew how. The class was in a different assembly. I tried

Type tableType = System.Type.GetType("CommonTables.callDetails");

to no effect.

For others looking up this question here's what I had to do:

After writing the following to debug:

Debug.WriteLine("DEBUG ASSEMBLY QUALIFIED NAME= " + callTableDef.GetType().AssemblyQualifiedName.ToString());

it gave me this as the assembly qualified name.

CommonTables.callDetails, callDetails, Version=3.0.4.0, Culture=neutral, PublicKeyToken=null

And that's the string I had to use in the getType() method. just the assembly.classname didn't work.

Ryan Muller