Creating an object using a literal string which contains the required type.

richard.cassell

New member
Joined
Jul 23, 2012
Messages
2
Location
Nottinghamshire, UK
Programming Experience
5-10
Hi all,

I'm writing some software which allows the user to draw diagrams containing nodes and controls, each representing an Object of a Class. As part of this, i'm coding save/load functionality using XML documents. My problem is that i have a tag in the XML which holds the Type of the object that the diagram control represents. This can be one of three Types: a Boolean, or either one of two custom-written classes (Let's call these Project.Class1 and Project.Class2)... Upon save, the program will get the types of the object (Just using a simple getType) and store the String literal into the XML tags... This works perfectly...

I now get around to the issue of loading the XML to open up an old diagram... The contents of the Type tag will now contain a literal String which i must use to determine what type my new Object needs to be... For a Boolean, this can be done by putting:

VB.NET:
Dim newObject As Object = Nothing

Dim objectType As Type = System.Type.GetType(StringFromXML)

If t Is GetType(Boolean) Then
     newObject = New Boolean
End If


The problem is, i can't use the above code for my custom-written Classes as they don't exist in System.Type....

So, what i need is to be able to read from XML the literal String of "Project.Class1".... And from that create a new object of type Project.Class1. I want to avoid comparing literal Strings in my code if possible (i.e. If StringFromXML = "Project.Class1" ...)

Can this be done?

Any help will be fantastic!

best Regards,

Cass
 
richard.cassell said:
they don't exist in System.Type....
Type.GetType will get you any Type object as long as the string contains enough information for the type to be found.
typeName parameter said:
The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
richard.cassell said:
And from that create a new object
Activator.CreateInstance(Type) method can be used.
 
Hi John!

Thanks for your quick response - with your advice i've managed to solve the problem!

I had a look at the AssemblyQualifiedName of my 2 classes and found that if i included the assembly name as part of the getType parameter it could find their type. I.e. getType("Project.Class1, PrjAssembly").

Thanks again for your help!

Cass
 
Back
Top