Reputation: 2597
I have situation where I have to call method of interface using reflection, like this
object x = null;
MethodInfo method = interfaceExists.GetMethod("ShutDown");
method.Invoke(x, new object[] { 4 })
As you can see I do not create instance of object! And, as I can supposed, I receive exception
Non-static method requires a target
And Question, Can I call method of interface using reflection without creating instance of interface and if YES, How I can do it ?
Upvotes: 8
Views: 8104
Reputation: 407
Can you call an interface method without creating an instance? No. Interfaces are for instance members; static class members aren't related to interfaces.
You might be able to get what you want by providing a static implementation of the interface,
public class MyImplementation : IMyInterface
{
public static readonly Instance = new MyImplementation();
private MyImplementation() { }
}
// ...then your code might look like:
MethodInfo method = typeof(IMyInterface).GetMethod("ShutDown");
method.Invoke(MyImplementation.Instance, new object[] { 4 })
Or you could make an extension method:
public static class MyExtensions
{
public static void ShutDown(this IMyInterface obj, ...) { ... }
}
// ...then your code might look like:
object x = null;
MethodInfo method = typeof(MyExtensions).GetMethod("ShutDown");
method.Invoke(x as IMyInterface, new object[] { 4 });
Upvotes: 1
Reputation: 27505
If you're absolutely sure the interface method won't impact object state (and that's generally a very bad assumption), you could create an instance without calling the constructor by calling FormatterServices.GetUnitializedObject. Personally, I would strongly recommend against this, as any number of bad things could happen when you call an interface method on an uninitialized type.
Upvotes: 13
Reputation: 115488
If the method is non-static, you have to create an object instance to use it. Since interfaces can't have static methods, you need to create an instance of an object with the interface on it to execute the method.
Upvotes: 4
Reputation: 1022
Your non-static interface method will eventually need to call a method that is implemented on an object. If the implementation of the method does not exist, then no real method can be called.
Upvotes: 2
Reputation: 5903
An interface has no implementation so you cant call its method without an instance of a object which implements that interface.
Upvotes: 1
Reputation:
If it is an instance method, you need an instance with which to call the method. Hence "instance" method.
Instance methods can have dependencies on instance variables, which reflection would not know about, so it cannot guarantee that an instance method does not alter the state of the instance of the type in which it is defined.
That's why you'll get those FxCop warnings about (paraphrasing here) "Make this method static as it does not alter the state of the class".
Upvotes: 10