Is it possible to use C # initialization syntax to pass a parameter?

In C #, using initialization syntax, I can say:

string[] mystrings = {"one", "two", "three"}; 

Is it possible to use the same array initialization syntax to convert this:

 string test = "This is a good sentance to split, it has at least one split word to split on."; string[] mystrings = test.Split(new string[] { "split" }, StringSplitOptions.RemoveEmptyEntries); 

In something like this:

 string test = "This is a good sentance to split, it has at least one split word to split on."; string[] mystrings = test.Split({ "split" }, StringSplitOptions.RemoveEmptyEntries); 

It seems like it should work, but I can't get it to do anything.

+4
source share
4 answers

Almost there:

 string[] mystrings = test.Split(new[]{ "split" }, StringSplitOptions.RemoveEmptyEntries); 
+7
source

It looks like you need a new string method:

 public static class StringExtensions { public static string[] Split(this string self, string separator, StringSplitOptions options) { return self.Split(new[] { separator }, options); } } 

Use it as follows:

 string[] mystrings = test.Split("split", StringSplitOptions.RemoveEmptyEntries); 

Now you have to decide whether or not to represent him.

For several delimiters, you can fix the options parameter (or put it in front, which will look unnatural based on other "overloads"):

 public static class StringExtensions { // maybe just call it Split public static string[] SplitAndRemoveEmptyEntries(this string self, params string[] separators) { return self.Split(separators, StringSplitOptions.RemoveEmptyEntries); } } 

And use:

 string[] mystrings = test.SplitAndRemoveEmptyEntries("banana", "split"); 
+2
source

You might have this syntax:

 string test = "This is a good sentance to split, it has at least one split word to split on."; string[] mystrings = test.Split(new[] { "split" }, StringSplitOptions.RemoveEmptyEntries); 

but I'm not sure you can simplify it further ...

+1
source

You can add an extension method:

  public static String[] Split(this string myString, string mySeperator, StringSplitOptions options) { return myString.Split(new[] {mySeperator}, options); } 

Then you can do:

  string test = "This is a good sentance to split, it has at least one split word to split on."; string[] mystrings = test.Split("split", StringSplitOptions.RemoveEmptyEntries); 
0
source

Source: https://habr.com/ru/post/1314974/


All Articles