+ 12

Difference beetween IList<> and List<> in C#.

I know that IList<> is an interface and List<> is a concrete class, but what are the real world uses and different situations where IList<> and List<> are used? In this example both IList<> and List<> gives same result. https://code.sololearn.com/cKZcTi0ZAHDd/?ref=app

18th Apr 2018, 5:40 AM
Rusty.Metal
4 Réponses
18th Apr 2018, 5:50 AM
Rusty.Metal
+ 6
IList<T> gives you everything you could get using IEnumerable<T>, plus operations that give you more control over a collection: Add, Delete, Count, Index access etc. List<T> is a concrete implementation of IList<T>. I would say that almost always it's better to expose IList<T> interface from your methods rather that List<T> implementation. And it's not just about lists - it's a basic design principle to prefer interfaces over concrete implementations. [stack overflow]
18th Apr 2018, 6:53 AM
᠌᠌Code X
᠌᠌Code X - avatar
+ 3
😐not learn yet
18th Apr 2018, 5:42 AM
Rishabh Singh
Rishabh Singh - avatar
0
The real world use is that when you use an interface such as IList you are giving the freedom to choose whatever class that implements the IList interface. If you used List, then you would be stuck with this implementation of the IList interface. Let's take an example: Say you have an interface called IAnimal that has one operation called Move(). And you also write two classes that implement this interface: Dog and Rabbit - public class Dog : IAnimal - public class Rabbit: IAnimal These two classes would implement the Move() method differently: - for Dog it would be: public void Move() {Console.WriteLine("I'm walking";} - for Rabbit it would be: public void Move() {Console.WriteLine("I'm jumping";} Now let's say that you have a class Owner that takes an animal as its pet: public class Owner { private IAnimal myPet; public Owner (IAnimal pet) { myPet = pet; } public LetPetRoamAround() {myPet.Move(); } } We can see that the Owner class can take in its constructor any class that implements IAnimal. That gives us the freedom to choose any pet we want! public class Program { public static void Main(){ IAnimal dog = new Dog(); IAnimal rabbit = new Rabbit(); Owner owner1 = new Owner(dog) Owner owner2 = new Owner(rabbit) owner1.LetPetRoamAround() // prints "I'm walking" owner1.LetPetRoamAround() // prints "I'm jumping" } } If we restricted ourselves so that the Owner class would only take Dog or Rabbit, then we would have to create mutiple of this Owner classes, one for each animal. That's why using interfaces is much more flexible and powerful.
19th Apr 2018, 5:54 AM
Mark