I never liked implicit operators (prefer extension methods) because it is hard to see visually when that cast/conversion happens in the code.
Imagine if you have example like below:
public static implicit operator Deal(string dealAsXml)
{
//convert the xml into Deal object
}
Above implicit operator helps you to cast/convert deal in Xml format into Deal Object.
Usually when you right click on a method, you can use "Find Usages" (or Alt+F7) on it, which is quite helpful, is there anything similar for implicit operators ?
I think that's another reason to use the Extensions methods where possible.
Maybe something like Resharper can do it, but I'm not sure. When I need to find usages, I do it the poor-man's way and remove the implicit operator, recompile and find the errors.
I suppose theoretically the compiler might then miss a case if it can use a different implicit operator (or switch to an "object" type overload of a method), but it tends to work for my usages. I'm sure there's a better solution, but it's worked for me so far.
EDIT: Just had a thought and tested it. Marking your implicit operator as [Obsolete]
will actually result in a compiler warning wherever you use it! I suppose this will catch those corner cases where there are other valid overloads that you'd miss having removed the implicit operator altogether.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With