Saturday 10 February 2018

Difference between List and IEnumerable in C#.

In this article, We will discuss about What is the difference between List and IEnumerable in C#.

List
------
- List is a Class.
- List is not read-only.
- We can able to add,delete items into List.

Example:-
-----------

      public ActionResult Index()
        {
            SampleEntities obj = new SampleEntities();

            var memList=(from x in obj.Memberships select x).ToList();

            return View();
        }

In the above example, We conside Index action method where memList is a List  and Whose add,delete method exists and Which is Shown in below figure,


IEnumerable
----------------
- IEnumerable is an Interface.
- IEnumerable is read-only.
- We can not able to add, delete items into IEnumerable because it is read-only.

Example:-
------------

public ActionResult Index()
        {
            SampleEntities obj = new SampleEntities();

            IEnumerable<Employee> objMem = _iemployeerepository.getListOfEmployee();

            return View();
        }

In the above example, We conside Index action method where memList is an IEnumerable  and Whose add,delete method does not exists and Which is Shown in below figure,


Note:- Depend upon the Situation we need to Use List and IEnumerable.

0 comments:

Post a Comment