Why "my,string".Split(',') works in .NET C#

.net, c#, split

Solution

The overload you're using uses a parameter array, basically. That's what the `params` part is. The compiler automatically wraps up your single argument into an array. So this:

var x = text.Split(',');

is equivalent to:

var x = text.Split(new char[] { ',' });

You can use a parameter array for your own methods too, with the `params` keyword:

static char GetChar(params char[] input)
{
    return input[0];
}

Note that the parameter array has to be the final parameter. That is why the overload you're using is the only overload of `Split` to use a parameter array. Look at the other overloads:

Split(Char[], Int32)
Split(Char[], StringSplitOptions)
Split(String[], StringSplitOptions)
Split(Char[], Int32, StringSplitOptions)
Split(String[], Int32, StringSplitOptions)

In each of these cases, the array is the first parameter, so you have to construct an array yourself:

var x = text.Split(new char[] { ',' }, 10); // Call the (char[], int) overload

Or using an implicitly-typed array:

var x = text.Split(new[] { ',' }, 10); // Call the (char[], int) overload

Problem

Why `"my,string".Split(',')` works in .NET C# ? The declaration of Split according to MSDN is `Split(Char[])`. MSDN String.Split Method I supposed that C# 5 converts the single char `','` to `char[] {','}`; But I must be wrong because the following code doesn't work: ``` static void Main() { GetChar(','); } static char GetChar(char[] input) { return input[0]; } ``` EDIT: Thanks to the Jon Skeet's answer I changed the argument to `params char[]` and it works proving the concept. ``` static char GetChar(params char[] input) { return input[0]; } ```

Original source