.NET: Unable to cast object to interface it implements

I hat the same problems with a library of mine providing “plugin”-functionality… I got it finally working… Here was my problem: I had one main assembly using plugins, one assembly with the plugin (Plugin.dll) AND (important) another assembly providing the plugin-functionality (Library.dll). The Plugin.dll referenced the main assembly (in order to be able to extend … Read more

Does System.Activator.CreateInstance(T) have performance issues big enough to discourage us from using it casually?

As always, the only correct way to answer a question about performance is to actually measure the code. Here’s a sample LINQPad program that tests: Activator.CreateInstance new T() calling a delegate that calls new T() As always, take the performance program with a grain of salt, there might be bugs here that skews the results. … Read more

Fast creation of objects instead of Activator.CreateInstance(type)

I did some benchmarking between these (I would write down the bare minimum details): public static T Instance() //~1800 ms { return new T(); } public static T Instance() //~1800 ms { return new Activator.CreateInstance<T>(); } public static readonly Func<T> Instance = () => new T(); //~1800 ms public static readonly Func<T> Instance = () … Read more

How to use Activator to create an instance of a generic Type and casting it back to that type?

Since the actual type T is available to you only through reflection, you would need to access methods of Store<T> through reflection as well: Type constructedType = classType.MakeGenericType(typeParams); object x = Activator.CreateInstance(constructedType, new object[] { someParameter }); var method = constructedType.GetMethod(“MyMethodTakingT”); var res = method.Invoke(x, new object[] {someObjectThatImplementsStorable}); EDIT You could also define an additional … Read more

C# Using Activator.CreateInstance

When using reflection you should ask yourself a couple of questions first, because you may end up in an over-the-top complex solution that’s hard to maintain: Is there a way to solve the problem using genericity or class/interface inheritance? Can I solve the problem using dynamic invocations (only .NET 4.0 and above)? Is performance important, … Read more

How to dynamically create generic C# object using reflection? [duplicate]

Check out this article and this simple example. Quick translation of same to your classes … var d1 = typeof(Task<>); Type[] typeArgs = { typeof(Item) }; var makeme = d1.MakeGenericType(typeArgs); object o = Activator.CreateInstance(makeme); Per your edit: For that case, you can do this … var d1 = Type.GetType(“GenericTest.TaskA`1”); // GenericTest was my namespace, add … Read more

tech