this popped into my head recently:
We have an Interface:
interface IPerson { }
and a Class that implements said Interface:
class Person : IPerson{ }
Now, what is the preferred way of initializing a Person-Variable, this:
Person person = new Person();
or:
IPerson person = new Person();
Using Type Inference and Intellisense
var person = new Person();
reveals that person is of type Person, instead of IPerson. Also I was thinking of something like this:
List<IPerson> persons;
vs. this:
List<Person persons;
What is the preferred way of declaring a variable or defining a Collection in this case, also in terms of future refactorings etc. If this is a duplicate question, please tell.
Best regards
CodePudding user response:
Usually, you prefer to use interfaces. Suppose that you have a list of Person
and you also have a kind of person, like SuperHero
:
class SuperHero : IPerson{ }
In this case, SuperHero
may inherit from Person
but as an example we may suppose that has not sense. So you have 2 classes implementing IPerson
.
If you have a variable of type Person
, you can't manage SuperHero
s. And if you have a List<Person>
you only can store Person
, not SuperHero
s.
If you need work with any IPerson
, you must use interfaces:
List<IPerson> list = new List<IPerson>();
list.Add(new Person());
list.Add(new SuperHero());
And a point about "var". If you use var, the compiler change var for the type that you use at right. You can force with a casting:
var person = (IPerson)new Person();
When you work with OLE automation and COM objects, in .NET you need an inplementation of the interfaces. That implementacion has the Class suffix. But you can work with the interfaces, without the Class suffix. More information here: https://docs.microsoft.com/es-es/archive/blogs/mshneer/vs-2010-compiler-error-interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead