Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create Object from Name

Status
Not open for further replies.

stsuing

Programmer
Aug 22, 2001
596
US
Say I have the string "System.Xml.XmlException". How can I create an object from that?

object[] args = new object[2];
args[0] = "Message";
args[1] = new Exception("Inner Exception Message");

Exception fooBar = (Exception)Activator.CreateInstance(typeof(System.Xml.XmlException), args);
Console.WriteLine(fooBar.ToString());


This works, but I can't figure out how to get the type from just the string "System.Xml.XmlException".
 
I think that CreateTypeFromProgID might be what you are after:
If not, you can also use the VB CreateObject function even though you are programming in C# by referencing the Microsoft.VisualBasic assembly:
Note that I believe these functions are for COM components, I'm not sure if they will work for .NET classes.

For the .NET classes, it looks like plain old GetType will work for you:
 
Code:
Type t = Assembly.LoadWithPartialName("System.Xml").GetType("System.Xml.XmlException");
Exception fooBar = (Exception)Activator.CreateInstance(t, args);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top