Reputation: 299
I have a lot of lists and I need to display them and to check items of the lists too.
I don't want to create a method for each list, instead I would like to access them like void Display()
and call the lists in my main method Display(name of the list)
I have a list named Family
and with the method I check if the input of the user is equal or not to it. As the result of checking, the user gets points for it.
My question is, is there a way to make this method general that I can access them like the example above, so I don't need as many methods as list, instead just one?
public void Check()
{
for (int i = 0; i < 99; i++)
{
if (ListOne.Family.Contains(UserInput()))
{
Console.WriteLine("Correct!");
points++;
// Exit if max points reached
if (points == ListOne.Family.Count)
break;
}
else
Console.WriteLine("Wrong!");
}
}
Upvotes: 0
Views: 63
Reputation: 151
The above example isn't necessarily the way to approach it, simply because of the lack of flexibility with the design. For example, if you try using generics you'll get something like this:
public void Check<T> (List<T> myList) where T : class
{
var listType = typeof(T);
switch (listType.Name)
{
case "List1":
break;
case "List2":
break;
}
}
The switch is code smell because if you have to add many lists, the switch becomes difficult to manage. Instead use the conditional to polymorphism approach and follow the strategy pattern or a simple factory pattern:
https://www.dofactory.com/net/strategy-design-pattern
https://www.dofactory.com/net/factory-method-design-pattern
Upvotes: 1