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.
This was my own stupid mistake. I forgot the inheritance between
Base
andDerived
...This works fine:
As does this:
And this: