Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to properly use an implementation of an interface

Tags:

c#

var

interface

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?

like image 818
user1481183 Avatar asked Dec 09 '22 20:12

user1481183


1 Answers

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.

like image 158
Jon Skeet Avatar answered Dec 11 '22 11:12

Jon Skeet