I have a 3rd party C++ DLL that I call from C#. The methods are static.
I want to abstract it out to do some unit testing so I created an interface with the static methods in it but now my program errors with:
The modifier ‘static’ is not valid for this item
MyMethod cannot be accessed with an instance reference; qualify it with a type name instead
How can I achieve this abstraction?
My code looks like this
private IInterfaceWithStaticMethods MyInterface;
public MyClass(IInterfaceWithStaticMethods myInterface)
{
this.MyInterface = myInterface;
}
public void MyMethod()
{
MyInterface.StaticMethod();
}
You can’t define static members on an interface in C#. An interface is a contract for instances.
I would recommend creating the interface as you are currently, but without the static keyword. Then create a class
StaticIInterfacethat implements the interface and calls the static C++ methods. To do unit testing, create another classFakeIInterface, that also implements the interface, but does what you need to handle your unit tests.Once you have these 2 classes defined, you can create the one you need for your environment, and pass it to
MyClass‘s constructor.