0

I'm using interfaces for unit testing in my project. My interface have functions as well as properties. I will be creating the object of interface class at the app startup as dependency and will be using throughout the application life cycle. Is it possible to re-instantiate the class pointing to interface on run time with the underlying type?

For example. This is what i do at app startup.

IPerson iperson = new Person();

Now once my API's are getting called i want to reinstatement this object again as per business logic. So again in my API logic how would i know what object type my interface is pointing to? Can i do something like this

// Type could be anything like Person,Person1,Person2 as all these classes implementing IPerson
Type p = iperson.Type 
 iperson = new p();
suresh rajput
  • 169
  • 2
  • 9
  • 3
    `iperson = Activator.CreateInstance(iperson.GetType()) as IPerson` – Alberto Oct 30 '19 at 12:11
  • 2
    @sureshrajput You don't instantiate an interface. An interface is not an object: it is a contract specification. It is an abstraction of the reality abstraction. You instantiate a class to have an object, then you can cast it into an interface reference. [What is the difference between an interface and a class](https://stackoverflow.com/questions/10914802/what-is-the-difference-between-an-interface-and-a-class-and-why-i-should-use-an/58174007#58174007) –  Oct 30 '19 at 12:11
  • @OlivierRogier The first comment is that i was looking for. – suresh rajput Oct 30 '19 at 12:22
  • @sureshrajput Yes. –  Oct 30 '19 at 12:23
  • @Alberto Thank you. Is there any performance issue or bad impact of using Activator.CreateInstance ? – suresh rajput Oct 30 '19 at 12:46
  • @sureshrajput as long as you don't pass any parameters to the constructor, the performance impact should be negligible. – Alberto Oct 30 '19 at 13:03

1 Answers1

0

It looks like that you do it wrong way. Reflection is for specific cases, and you have low probability to encounter this case.

I suggest you to create some generic IFactory<T> where T : new(), IInterface with method Create<T>(). If you will operate factory instead of direct type, it would give you an option to create new instances on-the-fly.