Suppose I have three projects in my sln.
(1) xyz.a{Class Lib}{no reference added}
(2) yzx.b{Class Lib}{added the reference of xyz.a}
(3) zxy.c{Console App}{added the reference of xyz.a}
Now, I need to create the instance of a class residing in yzx.b from within xyz.a using reflection.
And also this should be independent of the folder/directory-names.
I.e. even If I change the name of the directory of yzx.b, it should work.
Does anyone have any idea?
You might want to check out the Activator.CreateInstance() methods. Just pass it the name of the assembly and type.
If you don't have a compile-time reference to the assembly, you can still reference it at runtime with Assembly.Load().
First of all, Activator.CreateInstance() is a right way.
But, there is a more interesting way that is:
Just create expression that calls constructor:
Performance test:
Output:
But:
Just for curious.
You can use Activator.CreateInstance to create an instance easily (this also does various caching of reflection information to make repeated calls faster), or Type.GetConstructor if you want to reflect over the constructor itself as well as directly running it (via ConstructorInfo.Invoke)