C# 7: Tuples and generics

3.2k views Asked by At

C# 7 has a new feature which allows us to easily define tuples, so we can easily work with structures which contain multiple values.

Is there any way to use a tuple as a generic type constraint, or similar? For example, I've tried to define the following method:

public void Write<T>(T value)
    where T : (int x, int y)
{

}

I realise this particular example is fairly pointless, but I imagine other scenarios where it would be useful to have a tuple which contains a type derived from another type:

static void Main(string[] args)
{
    var first = new Derived();
    var second = new Derived();

    var types = (t: first, u: second);
    Write(types);

    Console.ReadLine();
}


public static void Write((Base t, Base u) things)
{
    Console.WriteLine($"t: {things.t}, u: {things.u}");
}

public class Base { }
public class Derived { }

This example doesn't work because first and second are of type Derived. If I make them of type Base this works fine.

1

There are 1 answers

0
Ian Newson On BEST ANSWER

This was my own stupid mistake. I forgot the inheritance between Base and Derived...

This works fine:

    public static void Write((Base t, Base u) things)
    {
        Console.WriteLine($"t: {things.t}, u: {things.u}");
    }

    public class Base { }
    public class Derived : Base { }

As does this:

    public static void Write<T>((T t, T u) things)
    {
        Console.WriteLine($"t: {things.t}, u: {things.u}");
    }

And this:

    public static void Write<T>((T t, T u) things)
        where T : Base
    {
        Console.WriteLine($"t: {things.t}, u: {things.u}");
    }