C # - How to use interface implementation correctly

public interface IMyInterface { List<string> MyList(string s) } public class MyClass : IMyInterface { public List<string> MyList(string s) } 

What's 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 correct way to use the IMyInterface implementation?

+4
source share
2 answers

The second is terrible. It is really equivalent

 IMyInterface inst = new MyClass(); 

but it doesn’t even check that MyClass implements the interface. This is just a way to use var , but explicitly specifying the type elsewhere. Hk.

As a rule, it is cleaner to declare variables using the interface type (in accordance with the above or the third option), if this is all you rely on, it makes it clear to the user that you do not need any additional members declared by the class. For more information, see "What does an interface program mean?" .

Note that none of this has anything to do with implementing an interface. MyClass is a class that implements an interface. It is simply related to using the interface.

+9
source

MyClass inst = new MyClass();

Creates an object using a specific type. Polymorphism is not achieved.

var inst = new MyClass() as IMyInterface

The compiler can infer what type it is based on casting and using var. Type IMyInterface ...

IMyInterface inst = new MyClass();

The best, in my opinion. Using MyInterface, you can achieve polymorphism by changing what inst points to runtime.

+5
source

Source: https://habr.com/ru/post/1438704/


All Articles