Search code examples
c#stringstring-matchingconsole.writelinemethod-group

c# console.writeline error when adding the operator + " new"


I am using using the following code and I want to add a string to the output, but i get this error

operator '+' cannot be applied to operands of type 'method group' and 'string'.

     class Program
{
   static void Main(string[] args)
        {
            string sample = "1a2b3c4d";
            MatchCollection matches = Regex.Matches(sample, @"\d");

            List<myclass> matchesList = new List<myclass>();

            foreach (Match match in matches)
            {
                myclass class1 = new myclass();

                class1.variableX.Add(match.Value);

                matchesList.Add(class1);
            }

        foreach (myclass class2 in matchesList)
            class2.variableX.ForEach(Console.WriteLine + " "); // <---- ERROR


        }


}

here is the class

public class myclass
    {
         public List<string> variableX = new List<string>();
    }

Solution

  • If you want to modify string before you use WriteLine method you have two possibilities:

    • class2.variableX.ForEach(s => Console.WriteLine(s + " "));

    or

    • class2.variableX.Select(s => s + " ").ForEach(Console.WriteLine);