4
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?

user1481183
  • 368
  • 2
  • 7
  • 19

2 Answers2

9

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.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

MyClass inst = new MyClass();

It creates an object using the concrete type. Polymorphism is not achievabe.

var inst = new MyClass() as IMyInterface

The compiler is able to infer which type it is based on the cast and using var. The type is IMyInterface...

IMyInterface inst = new MyClass();

The best in my opinion. By using MyInterface you can achieve polymorphism, changing what inst points to at runtime.

Lews Therin
  • 10,907
  • 4
  • 48
  • 72