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?
Join
there that is not having startIndex and endIndex arguments. (If you look around in the documentation of .NET's class library, you'll see method overloads are used almost everywhere...) – user2819245 Jun 28 '19 at 14:44int? end_index = null
? If user dosn't set it to something you can manually assign it in method:end_index = end_index ?? me.Length - 1;
– Aleks Andreev Jun 28 '19 at 14:45