gagro gagro -4 years ago 92
C# Question

int.Parse method without parentheses

Why can I invoke Parse method without parentheses since that method has 4 overloads?

For example in this case:

string[] aTemp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll(aTemp, int.Parse);

Answer Source

The signature for ConvertAll is actually this:

public static TOutput[] ConvertAll<TInput, TOutput>(
    TInput[] array,
    Converter<TInput, TOutput> converter
)

Which the compiler can infer to be:

public static int[] ConvertAll<string, int>(
    string[] array,
    Converter<string, int> converter
)

From the signature for Int32.Parse:

public static int Parse(
    string s
)

If you wanted to write out in long hand:

Converter<string, int> converter = new Converter<string, int>(Int32.Parse);
string[] aTemp = Console.ReadLine().Split(' ');
int[] a = Array.ConvertAll<string, int>(aTemp, converter);

Note: Converter<TInput, TOutput> is actually a delegate that takes as input a parameter of type TInput and returns a value of type TOutput.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download