# Pass IEnumerable<T> as an argument of method and repository pattern

I've seen tutorials of Unit Testing and I've never seen that IEnumerable<T> used as an argument of method. All authors use Repository pattern and Service layers to interact with data, that is, authors of tutorials get data in Service layer by Repository and there is no need to pass collections between the methods of Service layer.

However, I've written a simple quiz game which imitates Repository pattern and when I started writing unit test methods, then I realized that many of my methods has arguments type of IEnumerable<T>.

This is a simple quiz game where user can give simple answers to simple questions . For example, quiz asks question, then program will remember the answer of player and in the end program will calculate the overall score of the player answers. e.g. "How many continents are there on the Earth?", then quiz shows 4 possible answers, and then quiz remembers answers.

The whole code of my quiz game looks like this:

Model classes:

public class Answer
{
{
IdQuestion = idQuestion;
Content = content;
}

public int IdAnswer { get; }
public string Content { get; }
public int IdQuestion { get; }
}

public class Question
{
public Question(int idQuestion, string content)
{
IdQuestion = idQuestion;
Content = content;
}

public int IdQuestion { get; }
public string Content { get; }
}

{
{
IdQuestion = idQuestion;
}
public int IdQuestion { get; set; }
public int IdAnswer { get; set; }
}


Program class:

static void Main(string[] args)
{
IQuestionRepository questionService = Factory.CreateInstance<QuestionRepository>();
var questions = questionService.GetQuestions();

ICountPlayerScoreBySum playerScores =
Factory.CreateInstance<CountPlayerScoreBySumService>();

var winScoreString = ConfigurationManager.AppSettings.Get("WinScore");
int winScore = 0;
int.TryParse(winScoreString, out winScore);

Console.WriteLine( playerScore == winScore ?
$"Wow! You are a winner! Your score is {playerScore}" :$"Try again! It is just the lesson to win! Your score is {playerScore}");
}


The method GetPlayerAnswers of Program class:

private static IEnumerable<Answer> GetPlayerAnswers(IEnumerable<Question> questions,
{
{
};

foreach (var question in questions)
{
.Where(a => a.IdQuestion == question.IdQuestion)
.Select((a, i) => new PlayerAnswerViewModel {
Content = \$"{ IntToLetters(i)}. {a.Content}",
IdQuestion = a.IdQuestion,
PlayerKey = IntToLetters(i)
});

while (true)
{
Console.WriteLine();
{
}
else
{
.Where(a => a.PlayerKey == playerKey)
.FirstOrDefault();
question.IdQuestion,
playerKey));
break;
}
}
}

}


The methods AskQuestion and IntToLetters of Program class:

private static void AskQuestion(Question question,
bool showPossibleKeys = false)
{
if (showPossibleKeys)
{
Console.WriteLine();
Console.WriteLine("Possible keys are A, B, C or D");
}

Console.WriteLine(question.Content);
.ToList()
.ForEach(a => Console.WriteLine(a.Content));
}

public static string IntToLetters(int value)
{
string result = string.Empty;
result = (char)('A' + value % 26) + result;
return result;
}


Repositories:

public interface IAnswerRepository
{
}

{
}

interface IQuestionRepository
{
IEnumerable<Question> GetQuestions();
}


class AnswerRepository : IAnswerRepository
{
{
new Answer(7, 2, "More than 1"), new Answer(8, 2, "More than 2"), new Answer(9, 2, "More than 5"), new Answer(10, 2, "More than 6"),
}.Where(qa => questions
.Select(q => q.IdQuestion)
.Contains(qa.IdQuestion)
);
}
}


public class QuestionAnswerRepository : IQuestionAnswerRepository
{
{
}
.Where(qa => questions
.Select(q=>q.IdQuestion)
.Contains(qa.IdQuestion)
);
}
}


QuestionRepository:

public class QuestionRepository : IQuestionRepository
{
public IEnumerable<Question> GetQuestions()
{
return new List<Question>() {
new Question(1, "How many are there contintents?"),
new Question(2, "How many are there colours?"),
new Question(3, "What is the tallest tree?"),
new Question(4, "Do you like dolphins?"),
};
}
}


and CountPlayerScoreBySumService:

public class CountPlayerScoreBySumService : ICountPlayerScoreBySum
{
{
var sum = 0;
{
.FirstOrDefault();

sum += 1;
}
}

return sum;
}
}


and Factory service:

public class Factory
{
public static T CreateInstance<T>() where T : new()
{
return new T();
}
}


However, my signatures of methods looks like this. Many methods have arguments type of array:

private IEnumerable<Answer> GetPlayerAnswers(IEnumerable<Question> questions,
{
...
}


Is it okay? Is it a code smell to pass collections as arguments of a method? Or my quiz game is not properly designed? If yes, please be very kind, to advice me how design of an application can be improved.

In addition, I've pushed all my code of Quiz game code into GitHub.

• Could you edit your question please and explain what the quiz is about? We need this for context. Otherwise if you're not interested in a general review you should try Software Engineering. – t3chb0t Jan 22 at 9:23
• @t3chb0t Thank you for your attention, I've edited my question and explained what the quiz about. – StepUp Jan 22 at 9:29
• @Mathematics thanks for your comment. Upvoted. Could you show me please where Repository called as Service – StepUp Jan 23 at 8:44
• @Mathematics thank you very much for ERD. It is better than my tables as I have conjunction table to match a right answer to a question. This design of tables will give me less repositories. You should write your comments as an answer and I will upvote you. These are really helpful comments! – StepUp Jan 23 at 10:10

There is no general rule for using IEnumerable or not but there is one that says that you should use the most abstract representation of something because it gives you the most felxibility in what you can pass to such method because there would be fewer restrictions.

This means if you are iterating a collection and you do this only once then IEnumerable<T> is perfect because there is virtually nothing more general than this. However, if you plan to use Add or Count or iterate a collection multiple times then something meterialized would be more appropriate like IList<T> or ICollection<T>.

public int CountPlayerScoreBySum(IEnumerable<Answer> playerAnswers,
{
var sum = 0;
{
.FirstOrDefault();

sum += 1;
}
}

return sum;
}


Here, e.g. the first argument is ok, it's iterated only once but correctAnswers is used multiple times inside the loop so it probably should be something like IList<T> to make it more predictible and to inform the caller that you are going to use it more then once because it might otherwise execute some lengthly query.

You could also materialize it inside the method but this is not always a good idea and to make such decisions requires to take a look at the big picture and the entire design. Sometimes it's acceptable, another time it might not be the case.

So the bottom line is, don't stupidly use any type because some book says so but rather look carefully which type is the simplest one you can use and gives you the required felxibility at the same time. You have to decide in on case by case basis. You'll mostly end up with IEnumerable<T> anyway but make it a sensible decision and not I've heard that....

• Thanks for so great answer! Is it appropriate to ask you here or should I create another question to make a code review of my whole program? Is it possible to get comments of my quiz game? – StepUp Jan 22 at 9:55
• @StepUp your question is only 45min old --- give it some time, I'm sure more answers will appear later ;-) – t3chb0t Jan 22 at 9:57
• ok. Is it appropriate to ask you here or should I create another question to make a code review of my whole program? Is it possible to get comments of my quiz game? – StepUp Jan 22 at 9:58
• Why would you say that you should use the most abstract type for an output value? An ICollection<T> or an IList<T> is an IEnumerable<T>. So you lose no flexibility by returning a supertype, you gain flexibility, because you provide addtional functionality (which you might choose to ignore). An input value is a different story though. You want to put a minimum burden on the caller, so it is generally a good idea to ask for the minimum type that works for you. – Sefe Jan 22 at 13:29
• @Sefe AKA Postel's Law. – Ian Kemp Jan 22 at 13:32

There is nothing inherently wrong with using IEnumerable<T>, just as there would be nothing wrong with using List<T>. Whatever collection type you choose to accept or return is far more a matter of your application's needs than any style guide.

For example, if you were writing a public-facing API, you would likely want to be most permissible in what you accept in order to make it easy for clients to use that API. In that case, using IEnumerable<T> would allow any collection type (including arrays) to be passed to your methods.

On the other hand, if you were writing high-performance code that is internal to your application, you'd probably use List<T> and pass it between your (presumably private) methods (using concrete types is slightly faster than interfaces).

Remember that style guides are just that - guides. It's up to you the programmer to apply those guidelines intelligently and logically.

Changing comments to answer on OP request. I am not answering the direct question asked by OP but few comments about the overall architecture and design of there solution which may indirectly solve the issue OP is worried about, passing collections as parameters.

IQuestionRepository questionService = Factory.CreateInstance<QuestionRepository>();


Light heartly, never ever create an object from repository and name it a service, it makes code confusing for people me like who following onion architecture as show below,

Also in C# usually objects are initialled together WHEN you are only initiating them for calling a single function or maybe 2 and there is no risk of memory leak, it also makes code more readable. Did you thought about using DI ?

   IQuestionRepository questionService = Factory.CreateInstance<QuestionRepository>();
ICountPlayerScoreBySum playerScores = Factory.CreateInstance<CountPlayerScoreBySumService>();