Search code examples
c#castingexplicit-conversion

How can I create an explicit conversion from ThatType to ThisType by adding the conversion operator to ThisType


So, I have a class, and I want to be able to explicitly convert from ThatType to ThisTypes. Explicitely converting from ThisType to ThatType is pretty easy, it's just...

public static explicit operator ThatType (ThisType operand)
{
   return /*Some voodoo that creates a new ThatType logically equivalent to ThisType*/
}

It may just be me, but I see no immediate way to do the opposite. I want to take ThatType and explicitly convert it to ThisType. Can I do this while modifying ThisType, or do I have to have Access to ThatType's code? If the latter, is it just not possible to create an explicit conversion from ThatType of ThatType is provided by a library, like say, a Dictionary<T,T>?


Solution

  • You shouldn't need access to the code. Switching ThatType and ThisType (so ThatType is the parameter) allows you to define the operator.

    As some test code:

    class A { ... }
    class B {
        static implicit operator B (A operand) { ... }
    
        static void Main() { B b = new A() // works }
    }