Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reference previous parameter as parameter default value in a C# method?

I'm planning to write a C# extension method to only join a specific range of elements of a string array. For example, if I have this array:

+-----+  +-----+  +-------+  +------+  +------+  +-----+
| one |  | two |  | three |  | four |  | five |  | six |
+-----+  +-----+  +-------+  +------+  +------+  +-----+
   0        1         2          3         4        5

And I only want to join them using , from index 2 to index 4. I got three,four,five. If the user doesn't provide start index and end index, then my Join method will join all array elements. Below is my method signature.

public static class StringSplitterJoinner
{
    public static string Join(this string[] me, string separator, int start_index = 0, int end_index = me.Length - 1) {

    }
}

The problem is that the parameter end_index can't reference the first parameter me and it generates an error. I don't want the user to always provide start_index and end_index I want my method has some meaningful default values. In this case, how can I solve this problem?

like image 710
Just a learner Avatar asked Dec 22 '22 22:12

Just a learner


1 Answers

I suggest using overloading:

public static string Join(this string[] me, string separator) {
  //TODO: add parameters' validation

  return Join(me, separator, 0, me.Length - 1);
}

public static string Join(this string[] me, string separator, int start_index) {
  //TODO: add parameters' validation

  return Join(me, separator, start_index, me.Length - 1);
}

public static string Join(this string[] me, string separator, int start_index, int end_Index) {
  //TODO: implement logic here
}
like image 66
Dmitry Bychenko Avatar answered Jan 31 '23 05:01

Dmitry Bychenko