+ 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
4 Answers
+ 8
+ 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]
+ 3
đnot learn yet
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.