5

I have defined a new ViewModel class as follow:-

public class myviewmodel
{
    public IEnumerable<Question> Questions { get; set; }
    public decimal Total { get; set; }
    public string Message { get; set; }

}

but I can also defined it as

public class myviewmodel
{
    public List<Question> Questions { get; set; }
    public decimal Total { get; set; }
    public string Message { get; set; }

}

and this can also happen if I want to create a new model class; So what are the differences between the two appraches? BR

Anwar
  • 4,470
  • 4
  • 24
  • 30
John John
  • 1
  • 72
  • 238
  • 501

5 Answers5

3

I would stay away from List<T> in favor of ICollection<T> if possible: using "plain" list reveals too much about your implementation. IEnumerable<T> is a good choice as it gives you best flexibility in choosing the actual implementation, but it may not be sufficient if you need to find out the number of elements available to you without enumerating through the collection.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You could also use IList<Question>.

what are the differences between the two appraches?

The IEnumerable<> is more general (but also less functional). You can assign it from any Linq query without worrying about the actual list type.

The List<> version is more closely defined, you may have to convert to a List before you can assign it. It does give you more functionality.

You probably want something like IList<QuestionViewModel>

H H
  • 263,252
  • 30
  • 330
  • 514
0

IEnumerable is more abstract and is generally preferred to List or IList if possible. Simply because it's an interface and you have more implementation possibilities.

See this question.

Community
  • 1
  • 1
Alexander R
  • 2,468
  • 24
  • 28
0

It depends. In general you should prefer to return an interface such as ICollection, IList or IEnumerable as it gives you the option to change the actual implementation without breaking the code (as long as the implementation adheres to the interface contract).

Now as for which interface you should choose depends and what you need to do. For example if it should be possible to add items to the collection via Questions.Add() then you can't use an IEnumerable as it does not offer such an method.

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
0

I think others have already answered well, I would just like to add one thing:

IList is not always bad as opposed to ICollection as it should represent information that is already on memory (thus providing indexing and the Count property). In that case (information on memory) the ICollection would not be so good as a call to Count() might iterate over a collection even if the iterator is not lazy.

Samir Hafez
  • 214
  • 1
  • 7