Search code examples
c#listsyntax-error

C#: Removing an Item from List<String>... and the item is not recognized as a String?


newbie to C# here. In my code, I want to build a list of strings, then later pop the first element off the front of the list:

 1    public class foo
 2    {
 3        public List<String> listo;
 4
 5        public foo()
 6        {
 7            this.listo = new List<String>();
 8            listo.Add("Apples");
 9            listo.Add("Oranges");
10            listo.Add("Bananas");
11            RemoveAndPrintAll();
12        }
13
14        public void RemoveAndPrintAll()
15        {
16            while(listo.Count > 0)
17            {
18                System.Console.WriteLine(this.listo.RemoveAt(0));
19            }
20        }
21    }

MS Visual Studio tells me that line 18 has a syntax error, specifically this part:

this.listo.RemoveAt(0)

The error is CS1503, which doesn't have a very helpful description:

Argument 'number' cannot convert from TypeA to TypeB

The type of one argument in a method does not match the type that was passed when the class was instantiated. This error typically appears along with CS1502. See CS1502 for a discussion of how to resolve this error.

CS1502 is vaguely helpful:

This error occurs when the argument types being passed to the method do not match the parameter types of that method. If the called method is overloaded, then none of the overloaded versions has a signature that matches the argument types being passed.

So what the heck? The root of the problem is this:

  1. I create a List, then populate it with Strings
  2. Later, I try to remove Strings from the list... only the compiler doesn't think the elements are Strings any more.

If there something special I need to do here? Why would the compiler not recognize the elements' data type when it comes time to remove them from the list? Thank you


Solution

  • In your code,

    listo.RemoveAt(0) 
    

    will remove the 0th element from the list. It won't remove all elements.

    As a simple test, you can use this code to test:

        private static void RemoveElementsFromList()
        {
            var list = new List<string>() { "abc", "def", "efg" };
    
            for(int i = 0; i < list.Count; i++)
            {
                list.RemoveAt(0);
            }
            var size = list.Count; // here size = 1
        }
    

    You can do this;

    if(listo != null && listo.Any())
    {
        listo.RemoveRange(0, listo.Count);
        var size = listo.Count;
    }
    

    For push and pop functionality, use Stack however.