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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With