Alternative to tuples

How .net framework 4.0 supports Tuples. The Tuple class is not available in version 3.5. But is there a way to create my own MyTuple class in .net 3.5?

+3
source share
1 answer

Yes. You can create your own tuples. This is nothing complicated. Here is an example with Tuple<T1, T2>and Tuple<T1, T2, T3>.

public class Tuple<T1, T2>
{
    public Tuple(T1 item1, T2 item2)
    {
        this.Item1 = item1;
        this.Item2 = item2;
    }

    public T1 Item1 { get; private set; }

    public T2 Item2 { get; private set; }
}

public class Tuple<T1, T2, T3>
{
    public Tuple(T1 item1, T2 item2, T3 item3)
    {
        this.Item1 = item1;
        this.Item2 = item2;
       this.Item3 = item3;
    }

    public T1 Item1 { get; private set; }

    public T2 Item2 { get; private set; }

    public T3 Item3 { get; private set; }
}

And here is the static factory class for instantiating Tuple:

public static class Tuple
{
    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);
    }
}

Now you can write the following:

var myTuple = Tuple.Create(4, "oh yes baby");

Greetings

+5
source

Source: https://habr.com/ru/post/1793622/


All Articles