-1

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>?

Sidney
  • 624
  • 7
  • 20
  • You could spend 30 seconds to write the code, compile it, and find out. It'd take you much less time than you spent writing this question. – Servy Mar 10 '16 at 16:27
  • @Servy That's probably entirely true, but the thing is is that I don't know where to start. =/ I'm not doubting it's easy, but so is changing your oil, or basket weaving, or pottery, or welding *if you know how* – Sidney Mar 10 '16 at 16:29
  • But you already know how to create an explicit conversion from one type to another. I know you know this, because you showed the code for how to do this in your question. You merely need to adjust the types for the conversion you want to perform, and then you'll be able to find out whether or not it works. – Servy Mar 10 '16 at 16:32
  • @Servy Thank you, although I would argue it's not entirely obvious that you can create that sort of conversion to a Type from within that type's definition. Unfortunately most googling and research returned results to get from ThisType to ThatType, but not the other way around. If you want to post it as an answer, I'll accept it, otherwise I'll just post it. – Sidney Mar 10 '16 at 17:03

1 Answers1

1

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 }
}
Isaac van Bakel
  • 1,772
  • 10
  • 22