Unfortunately, C# or .NET does not support duck typing in this particular context.
For a type to implement a particular interface, it will have to explicitly declare that it implements this interface. You say "satisfy" now, but this has no meaning for C# or .NET.
Does the type MyClass
implement IInterface
? No, sadly it doesn't.
This declaration:
public class MyClass { }
Declares a class that inherits System.Object
, and does not implement any interface.
The fact that the interface contains no methods or properties does not in any way make it match up with this type. The class still does not implement this interface.
The only way for a class to implement an interface is to make it explicit:
public class MyClass : IInterface { }
So no, there is no way to force C# or .NET to consider that class as one implementing this interface.
The common ways to handle this is to make a wrapper class (ie. a class that implements IInterface
and contains a MyClass
, delegating all methods and/or properties to the contained MyClass
instance), or, you know, actually implement the interface.
To conclude, the only way to make this code compile:
IInterface myVariable = new MyClass();
is to make MyClass
explicitly either implement the interface:
class MyClass : IInterface { }
or to inherit from another class that implements it:
class BaseClass : IInterface { }
class MyClass : BaseClass { }