Using the Contains() and Add() methods on my list of string but it doesn't run

Viewed 46

In the code below I'm running the RepeatedNames method on a list called listOfNames with some of them being repeated. So the method is supposed to store the repeated ones in another list (_repeatedNames) and printing them out in the console. But it doesn't run.

Just to mention: I'm new to C# and trying to learn in a practical way through coding, so there must be something obvious that I'm doing wrong.

static void Main(string[] args)
{
        List<string> listOfNames = new List<string>() { "Sam", "Mark", "Nick", "Laura", "Mark", "Helen", "Nick" };
        RepeatedNames(listOfNames);
}


private List<string> _names = new List<string>();
private List<string> _repeatedNames = new List<string>();

static void RepeatedNames(List<string> NameCollection)
{
        foreach (var name in NameCollection)
        {
        if (!_names.Contains(name))
        {
                 _names.Add(name);
        }
        else
        {
                 _repeatedNames.Add(name);
                 Console.Write(name + "\t");
        }  
}
1 Answers

The obvious mistake I made was, not using the word static in my lists' declaration.

Every time the foreach loops through, it's dealing with each item in the list, so in order to be able to use the Contains() and Add() methods on my lists (which are non-static), I should create an object instance of them. If not, I should mark my lists as static so that no instance of them is needed when invoking those two methods on them.

So the code in the question is missing the keyword static, and it'll look like as below:

private static List<string> _names = new List<string>();
private static List<string> _repeatedNames = new List<string>();
Related