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
but it doesn’t even check that
MyClassimplements the interface. It’s just a way of usingvarbut 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.
MyClassis the class implementing the interface. This is just to do with using an implementation of the interface.