c# - Dealing with cumbersome string.Split overloads? -


the string.split() in .net can cumbersome use. many overloads must specify array when passing single delimiter (in fact 1 overload marked params).

is there such alternative? there way of accomplishing task without creating arrays.

the issue there 2 conflicting best practices in developing such api(they both practices , not conflict except in particular case):

  • only params parameter can/must appear last parameter.
  • overloads of function should maintain same parameter ordering.

so have first overload:

split(params char[] separator) 

which leverages params keyword don't explicitly need create array done implicitly.

the other overloads follow second guideline, maintaining separator parameter first parameter, therefore cannot specify params keyword since can appear on last parameter.

so it's design choice balanced between 2 best practices. in case, followed maintain-parameter-order guideline, , did not use params keyword on other overloads because not allowed when followed others parameters.

solution

you implement own static methods or extensions separator parameter last parameter, , therefore can specify params it. make decision favor first guideline , disregard second:

public string[] split(int count, stringsplitoptions options, params char[] separator) 

you have careful when versioning class libraries , evolving apis. there scenarios introduction of new params overload allow match old overloads ambiguously , break code of projects consuming it.

alternative

if want avoid writing overload extensions, craig w. points out "x".tochararray() might more intuitive way generate single item array(or "xyz".tochararray() multiple single character delimiters). should note means adding bit of runtime processing small negligible.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -