0

I have the following

public interface IImportProcess
{
    Task Process(int id);
}

public class Sally:IImportProcess
{
    public async Task Process(int id)
    {...}
}
public class Bob:IImportProcess
{
    public async Task Process(int id)
    {...}
}

say I have "Sally" in my db, and I want to instantiate an object Sally but i dont want a concrete object, I simply want to get the interface version of it so I can just call .Process() on it and it would call the .Process() of Sally because the string/class it was created from is Sally

Same would be if I pass "Bob" then it would instantiate based on Bob class

Assuming all these classes are in the same assembly so I can use reflection and if possible Activator so I can do the following

var cls = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("Sally") as IImportProcess;
await cls.Process(1);

cls seems to always return null when it should not be null

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Zoinky
  • 4,083
  • 11
  • 40
  • 78
  • 8
    So what happens with your code? What is your question? – DavidG Feb 06 '20 at 16:13
  • I am confused by this question because the title does not match the code example, which does not use generics at all. – John Wu Feb 06 '20 at 16:16
  • @JohnWu added the question, reopen pls – Zoinky Feb 06 '20 at 16:17
  • 1
    You need to use the fully qualified name for the type, try `Your.Namespace.Sally` – DavidG Feb 06 '20 at 16:19
  • https://stackoverflow.com/questions/223952/create-an-instance-of-a-class-from-a-string – DavidG Feb 06 '20 at 16:20
  • Cannot reproduce: https://dotnetfiddle.net/a2wOqG – canton7 Feb 06 '20 at 16:20
  • As a side note: it's normally much better to use `typeof(SomeTypeWhichExistsInYourAssembly).Assembly` rather than one of the `Assembly.GetXXXAssembly()` methods. E.g. `typeof(IImportProcess).Assembly`. Although `Activator.CreateInstance` is probably even better here. – canton7 Feb 06 '20 at 16:21
  • @canton7 I assume OP has the class in a different namespace which is why you can repro and they can't. – DavidG Feb 06 '20 at 16:23
  • @DavidG You're probably right (I previously upvoted your comment saying that). I generally try and avoid making assumptions like that: if the OP posts code which doesn't repro, they can go away and make it more like their actual code until it does. At that point, they'll discover what the difference is, and learn a useful debugging skill. – canton7 Feb 06 '20 at 16:24

0 Answers0