Click here to Skip to main content
15,921,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have follwing scenario:
XML
List<ABC> abc = new List<ABC>()
           {
               new ABC { a = "YYY", b = "rrrr" },
               new ABC { a = "www", b = "ddd" }
           };

          //not working
           string result= abc.ForEach(a => ABC.MyMethod(a.b));
           //working
          var result1= abc.Select(a => ABC.MyMethod(a.b)).ToList();


The first LINQ expression is giving error saying "Cannot implicitly convert type 'void' to 'string'" while the second one is working.
Can anybody explain why?

This is my method body:
C#
public static string MyMethod(string input)
       {
           var c = input;
           return c;
       }
Posted
Updated 8-Oct-15 8:32am
v2
Comments
BillWoodruff 8-Oct-15 22:47pm    
What does a.b refer to ? there's an "a" in the class ABC that has a field or something accessed through .b ?

1 solution

Well... it's pretty obvious! :laugh:
The second one first:
From a collection of ABC objects, select the return value - which is string - and convert it to a list of strings. Nothing funny there.

The first one though just takes a look at the MSDN documentation: List<T>.ForEach Method[^] and you will see it returns a void - and there is nothing you can cast a void to at all!
ForEach doesn't return a collection, it doesn't return anything.
 
Share this answer
 
Comments
Maciej Los 8-Oct-15 15:14pm    
"Nothing funny there" - You're wrong, Paul... :laugh: ;)
+5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900