I have two structs (Point and Size) with Deconstruct() method. Both return (int, int) tuple.
I'm trying to deconstruct them to (int, int) tuple variable in switch without success. The compiler gives me the error:
Cannot implicitly convert type 'Size' to '(int, int)'.
How can I deconstruct these both structs to one tuple to have the ability to use it in the second switch expression?
using System;
class Program
{
static string DescribeSize<TDeconstructable>(TDeconstructable deconstructableStruct)
where TDeconstructable : struct
{
(int, int) xy;
switch (deconstructableStruct)
{
case Size size:
xy = size; //CS0029 error: Cannot implicitly convert type 'Size' to '(int, int)'
break;
case Point point:
xy = point; //CS0029 error: Cannot implicitly convert type 'Point' to '(int, int)'
break;
default:
xy = (0, 0);
break;
}
return xy switch
{
(0, 0) => "Empty",
(0, _) => "Extremely narrow",
(_, 0) => "Extremely wide",
_ => "Normal"
};
}
static void Main(string[] args)
{
var size = new Size(4, 0);
var point = new Point(0, 7);
Console.WriteLine(DescribeSize(size));
Console.WriteLine(DescribeSize(point));
}
}
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public void Deconstruct(out int x, out int y)
{
x = X;
y = Y;
}
}
public readonly struct Size
{
public int W { get; }
public int H { get; }
public Size(int w, int h)
{
W = w;
H = h;
}
public void Deconstruct(out int w, out int h)
{
w = W;
h = H;
}
}