0

I am trying to add support for implicit casting between two types that don't have implicit casting.

I tried to do it via extension method:

//static classes cannot contain user defined operators
public static implicit operator Vector2D(this float2 a) => new(a.x, a.y);

But this is not allowed. Why does C# not allow extension methods for implicit casting ? What is the best way to get around this?

WDUK
  • 1,412
  • 1
  • 12
  • 29
  • 1
    _"What is the best way to get around this?"_ - suck it up and use a `.ToVector2D( this float2 value ) =>` extension method. – Dai Jun 22 '23 at 02:02
  • Other than (admittantly unlikely) security risks - I think the main reason is that it would make method overload selection difficult to reason-about. – Dai Jun 22 '23 at 02:06
  • _"you cannot use explicit operators in static classes"_ - that statement is meaningless: a `static class` cannot be used to represent a value, therefore there is nothing to convert in the first place. – Dai Jun 22 '23 at 02:07
  • Right but its an extension method so i presumed it would work because its linked to a type. – WDUK Jun 22 '23 at 02:11
  • C# requires all `operator` members involving type `T1` (say, the typeof the left-hand operand of `==`, or in `implicit operator` and `explicit operator`: either the "from" type or the "to" type to be defined as a `static` member of one of those types - so given that a `static class` cannot be used to represent values, it then follows that you cannot define an `implicit operator` or `explicit operator` within a `static class` because _both_ types will be unrelated to the `static class` that contains them - and in-addition to that, C# also simply does not permit _extension_ `operators` either. – Dai Jun 22 '23 at 02:14
  • I deleted my earlier comments which were mostly speculation and conjecture - while I still believe the C# language designers want to avoid non-local effects, especially non-local effects that can be changed unexpectedly - I can't find a source to back it up. – Dai Jun 22 '23 at 02:18

0 Answers0