Is there a class existing in .NET Framework 3.5 that would be equivalent to the .NET 4 Tuple?
I would like to use it in order to return several values from a method, rather than create a struct
.
A tuple is a data structure that has a specific number and sequence of elements.
A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don't want to create a new class.
Tuple types are immutable. Data members of System. ValueTuple types are fields.
Tuples can be used to store a finite sequence of homogeneous or heterogeneous data of fixed sizes and can be used to return multiple values from a method. Tuples are nothing new - they have been around for quite some time now in programming languages like F#, Python, etc.
No, not in .Net 3.5. But it shouldn't be that hard to create your own.
public class Tuple<T1, T2> { public T1 First { get; private set; } public T2 Second { get; private set; } internal Tuple(T1 first, T2 second) { First = first; Second = second; } } public static class Tuple { public static Tuple<T1, T2> New<T1, T2>(T1 first, T2 second) { var tuple = new Tuple<T1, T2>(first, second); return tuple; } }
UPDATE: Moved the static stuff to a static class to allow for type inference. With the update you can write stuff like var tuple = Tuple.New(5, "hello");
and it will fix the types for you implicitly.
I'm using this in my pre-4 projects:
public class Tuple<T1> { public Tuple(T1 item1) { Item1 = item1; } public T1 Item1 { get; set; } } public class Tuple<T1, T2> : Tuple<T1> { public Tuple(T1 item1, T2 item2) : base(item1) { Item2 = item2; } public T2 Item2 { get; set; } } public class Tuple<T1, T2, T3> : Tuple<T1, T2> { public Tuple(T1 item1, T2 item2, T3 item3) : base(item1, item2) { Item3 = item3; } public T3 Item3 { get; set; } } public static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3>(item1, item2, item3); } }
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