Reputation: 1127
Consider the code below:
void fun1(string typeName)
{
object adap = Activator.CreateInstance(typeName);
adap.dowork(); //won't compile because of strongly typed.
}
Using Activator.CreateInstance()
we can easily create instance of any type, but if we don't know the typename at design time, it is not possible downcast it to its actual type either.
My question is, how can we call a function of instance created by Activator.CreateInstance
if we cant downcast it to its appropriate type as we dont know the typename at design time, but we know that the function exists.
I hope I've made myself clear.
Upvotes: 2
Views: 1321
Reputation: 9116
If you know that typeName
has the method doWork
, it would be better that your type implements an interface like:
interface IDoWorkSupport
{
void DorWork();
}
then you can make your code like:
var adap = (IDoWorkSupport) Activator.CreateInstance(typeName);
adap.DoWork(); //this now compiles
In this case its a more object-oriented solution.
Upvotes: 0
Reputation: 8510
One thing you can do is assign it to a dynamic
type.
dynamic adap = Activator.CreateInstance(typeName);
adap.dowork(); //this now compiles
It is also possible to invoke a method dynamically using reflection if you know the method name.
Upvotes: 6
Reputation: 1062770
The best option is to know some common interface or base-class, and cast to that. However, if that is not possible you can duck-type by using
dynamic adap = ...
And the rest of your code as-is.
If that isn't possible (wrong .net version etc) then you'll have to use reflection.
Upvotes: 3