开发者

Undocumented overload of string.Split()?

According to both Intellisense and MSDN doc on string.Split, there are no parameterless overloads of string.Split. Yet if I type in

string[] foo = bar.Split();

It compiles. And it works. 开发者_Go百科I have verified this in both Visual Studio 2008 and 2010. In both cases intellisense does not show the parameterless overload.

Is there a reason for this? Are there any other missing overloads from the MSDN/Intellisense docs? Usually browsing through overloads in intellisense is how I best determine which overload to use. I'd hate to think I am missing other available options throughout the .Net framework.

EDIT: as shown above, it splits on whitespace.


That is because Split has a params overload. Giving no parameters is the same as giving an empty array. In other words, you are calling this overload.

"some text".Split();

Is the same as:

"some text".Split(new char[0]);

Here is the documentation on the params keyword. As you probably know, it is used for giving a method a variable number of parameters. That number may be zero.


I bet it's matching this String.Split overload:

public string[] Split(params char[] separator)
{
    return this.Split(separator, 0x7fffffff, StringSplitOptions.None);
}

0 arguments is acceptable for this function. Given no separators, it defaults to white space.


Actually what you are calling here is string.Split(params char[] separator)

params (C# reference)

You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.


It has to do with a weakness of exposing parameters as 'params array[]'. See the signature of the following method as documented in MSDN, so obviously you are passing in an empty array.

public string[] Split(params char[] separator)


String.Split() has a number of overloads; you are correct that none of those overloads is parameter-less, however, one of them is varadic: String.Split(params char[]). The variable length portion of the argument list can be any number of arguments, including zero -- that is the overload you're invoking here.


public string[] Split(params char[] separator)

params is 0 or more

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜