Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom struct with casting to another type in C#

Tags:

c#

I have a struct currently that i can cast to another type like this:

    public static implicit operator Vector2(Complex a)
    {
        return new Vector2(a.Real,a.Imaginary);
    }

At the moment how ever this is allowed automatically:

Vector2 a = new Complex(b,c); //valid

But i would prefer it did not automatically allow this. But rather only allow:

Vector2 a = (Vector2) new Complex(b,c);

How can i have a restricted casting with this kinda behaviour for my struct the same way floats casting to ints work?

like image 654
WDUK Avatar asked Mar 01 '26 12:03

WDUK


1 Answers

Just change the implicit to explicit:

public static explicit operator Vector2(Complex a)

The implicit part tells the compiler that it can do it without the code specifying the conversion. See the Microsoft documentation for user-defined operators for more details.

like image 183
Jon Skeet Avatar answered Mar 04 '26 01:03

Jon Skeet