Or if you just want to avoid the extra variable name for readability sake, you could do something like that (C#7+):
public static void Deconstruct<T>(this IList<T> self, out T v1, out T v2) {
v1 = self.Count > 0 ? self[0] : default;
v2 = self.Count > 1 ? self[1] : default;
}
On another static class where you write your extension methods.
And then use it like:
var (a, b) = "1,2".Split(','); // a = "1"; b = "2";
Obviously, this can be extended for more than two variables, but unfortunately, you have to write another method as far as I know.
For example:
public static class Ex {
public static void Deconstruct<T>(this IList<T> self, out T v1, out T v2) {
v1 = self.Count > 0 ? self[0] : default;
v2 = self.Count > 1 ? self[1] : default;
}
public static void Deconstruct<T>(this IList<T> self, out T v1, out T v2, out T v3) {
v1 = self.Count > 0 ? self[0] : default;
v2 = self.Count > 1 ? self[1] : default;
v3 = self.Count > 2 ? self[2] : default;
}
public static void Deconstruct<T>(this IList<T> self, out T v1, out T v2, out T v3, out T v4) {
v1 = self.Count > 0 ? self[0] : default;
v2 = self.Count > 1 ? self[1] : default;
v3 = self.Count > 2 ? self[2] : default;
v4 = self.Count > 3 ? self[3] : default;
}
}
And use it like:
var (a,_,_,d) = "1a,2b,3c,4d".Split(','); // a = "1a"; d = "4d";
As a side effect, now you can deconstruct any array.
var (first,second) = new [] { 1,2 }; // first = 1; second = 2;