3

Is there a functionality for C# 7 ValueTuple similar to Python's slicing? The syntax for value tuples in C# is similar to Python but I can't find an elegant way to get subtuple from tuple for example.

In Python 3:

 tuple = (1,2,3)
 subtuple = t[:2]   #subtuple is (1, 2)

In C# 7:

 var tuple = (1,2,3)   //Very similar to Python!
 var subtuple = (tuple.Item1, tuple.Item2)  //Not very elegant, especially for bigger tuples
SENya
  • 1,083
  • 11
  • 26
  • 7
    AFAIK, the answer here is simply: "no" – Marc Gravell Apr 10 '18 at 08:12
  • 2
    In Python it is like an array but here you have something like an object – Farshad Apr 10 '18 at 08:14
  • check if this helps you : https://stackoverflow.com/questions/18558353/how-to-get-tuple-property-by-property-index-in-c – Farshad Apr 10 '18 at 08:19
  • Can probably only be done with reflection, although not as elegant as Python. Perhaps will be a feature in a future C# version? – silkfire Apr 10 '18 at 08:23
  • 2
    @silkfire it would be hard to do with reflection because the intent is usually to respect the logical *names* of the elements, and those names *aren't available* to any reflection API; it would have to be a language feature. Also, the expansion / roll-around of the final "everything else" value in large tuples would be *really* hard to deal with as reflection. – Marc Gravell Apr 10 '18 at 08:27
  • It's a pity. I thought C# value tuples were inspired by Python so the functionality is similar. – SENya Apr 10 '18 at 08:28
  • @SENya the idea was having named, temporary objects with high performance. – Mafii Apr 10 '18 at 09:06
  • 3
    C# is statically typed, so for that reason alone python syntax is not possible, because type of `subtuple` in your example cannot be determined at compile time (it can be ValueTuple, or ValueTuple etc). – Evk Apr 10 '18 at 09:08

1 Answers1

5

No, there is nothing like that in C#. Due to the statically-typed nature of C#, a feature like that couldn't work with arbitrary expressions for the slice points.

I think that the closest you can get is to create a bunch of extension methods that have the slice points embedded in their names. E.g.:

public static (T1, T2) Take2<T1, T2, T3>(this (T1, T2, T3) tuple) =>
    (tuple.Item1, tuple.Item2);

var tuple = (1,2,3);
var subtuple = tuple.Take2();

Note that if the tuple members have names, this will strip them off.

svick
  • 236,525
  • 50
  • 385
  • 514