Anyone have an idea on what framework classes handle instantiating types from entries in configuration like this:
type="SomeAssembly, SomeVal, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
I am needing to do the same thing and would rather use part of the framework if possible. Thanks!
John
-
-
Type t = Type.GetType("Namespace.SomeType, SomeAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
object instance = Activator.CreateInstance(t); -
Doh! I guess I should have known that. Thanks!
-
Sven Groot wrote:
Type t = Type.GetType("Namespace.SomeType, SomeAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
object instance = Activator.CreateInstance(t);
It's a little bit different:
Type t = Type.GetType("Namespace.SomeType, SomeAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", true);
object instance = Activator.CreateInstance(t);
True to fire an exception if the type couldn't be created. Without this flag GetType returns null if the type couldn't be fetched. -
Thanks. I definately need to be able to catch the exception.
-
JParrish wrote:Thanks. I definately need to be able to catch the exception.
you could also remove the true flag and check the returned type for being null. If null, you could throw an exception or do something else...
Would also be a valid option. -
If you need to get multiple types from the same assembly, it's more performant to load an assembly instance first and then call GetType mutiple times off of that assembly instance.
Example:
Assembly assembly = Assembly.Load("MyAssembly");
SomeType someType = assembly.GetType("MyAssembly.SomeType");
AnotherType anotherType = assembly.GetType("MyAssembly.AnotherType");
Using this method you can cache the assembly object for multiple type retrievals. Also remembe if you are retrieving an inner type, the + syntax is needed i.e.
InnerType innerType = assembly.GetType("MyAssembly.AntotherType+InnerType");
Cheers
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.