public interface IMyInterface
{
List<string> MyList(string s)
}
public class MyClass : IMyInterface
{
public List<string> MyList(string s)
}
What is the difference between:
[Method]
MyClass inst = new MyClass();
...
Or:
[Method]
var inst = new MyClass() as IMyInterface;
...
Or:
[Method]
IMyInterface inst = new MyClass();
...
What is the proper way to use an implementation of IMyInterface?
The second is horrible. It's really equivalent to
IMyInterface inst = new MyClass();
but it doesn't even check that MyClass
implements the interface. It's just a way of using var
but specifying the type explicitly elsewhere. Ick.
Generally it's cleaner to declare variables using the interface type (as per the above, or the third option) if that's all you're relying on - it makes it clear to the user that you don't need any extra members declared by the class. See "What does it mean to program to an interface?" for more information.
Note that none of this has anything to do with implementing the interface. MyClass
is the class implementing the interface. This is just to do with using an implementation of the interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With