C# ConvertAll syntax

3.6k Views Asked by At

I'm trying to understand the syntax for ConvertAll in C#, and despite looking at several examples and trying to copy them, I can't get the following line containing s2 to compile; VSE2013 says

"Error 1 No overload for method 'ConvertAll' takes 1 arguments ".

what does the error message mean? Where am I going wrong? And yes, I understand that Select is much better to use in these situations, for several reasons. Thanks!

static int Main(string[] args)
{ 
    Console.WriteLine ("jello world");

    int s1 = args.Sum(st => int.Parse(st));
    int s2 = args.ConvertAll(x => int.Parse(x)).Sum();
    int s3 = args.Select(st => int.Parse(st)).Take(2).Sum();
    return 0;
}
2

There are 2 best solutions below

4
On

Change args.ConvertAll(x => int.Parse(x)).Sum(); to Array.ConvertAll(args, x => int.Parse(x)).Sum();.

As the error message told you, 'ConvertAll' does not take 1 argument, so that should clue you in to the fact that you need more arguments (in this case, the array).

See MSDN for proper usage of Array.ConvertAll.

0
On

You are calling ConvertAll on an actual array instance - but ConvertAll is a static method, hence does not have access to the content of your array - you need to pass in the array itself as the first parameter so that it can use it - and since it's a static method should call it on the Array class itself:

int s2 = Array.ConvertAll(args, x => int.Parse(x)).Sum();

Also shorter using a method group:

int s2 = Array.ConvertAll(args, int.Parse).Sum();