✅ Why is an explicit cast needed even though the implicit cast operator is available?

No explicit cast is needed.
var (x, y) = GetPoint();
static (float re, float im) GetPoint() => (1, 0);
var (x, y) = GetPoint();
static (float re, float im) GetPoint() => (1, 0);
But why does the following need explicit cast even though an implicit conversion operator has been implemented?
//var (x, y) = new Complex(1, 0); <== Error!

var (x, y) = ((float, float))new Complex(1, 0);

class Complex(float re, float im)
{
public float Re { get; set; } = re;
public float Im { get; set; } = im;
public static implicit operator (float re, float im)(Complex c) => (c.Re, c.Im);
}
//var (x, y) = new Complex(1, 0); <== Error!

var (x, y) = ((float, float))new Complex(1, 0);

class Complex(float re, float im)
{
public float Re { get; set; } = re;
public float Im { get; set; } = im;
public static implicit operator (float re, float im)(Complex c) => (c.Re, c.Im);
}
5 Replies
JochCool
JochCool4mo ago
I think it's because the syntax var (x, y) is deconstruction syntax, so it will try to call a destructor
jcotton42
jcotton424mo ago
var (x, y) = is performing a deconstr--yeah that it's not creating a tuple
JochCool
JochCool4mo ago
This works:
C#
(float, float) variable = new Complex(1, 0);
C#
(float, float) variable = new Complex(1, 0);
i like chatgpt
i like chatgpt4mo ago
Ok. Thanks.