Type conversion operators in C# revisited

Craig had a rather strong reaction to my post about type conversion operators in C#, and after some back and forth in the comments to his post, I'm now convinced that it's probably better to avoid them altogether.
 
While it is convenient to be able to just cast one object to another, the problem is that it really messes with the concept of identity. Bertrand Le Roy expressed a similar concern to Craig's in a comment to my post, and put it quite succinctly:
 
"IMHO it all boils down to (someObject == (SomeType)someObject) being false with your code, which looks very wrong. "
 
Because the type conversion operator allocates a new object of the desired type, this expression will return false, and I agree that this just feels wrong, and can certainly lead to some unexpected behavior if you're not careful.
 
So I'm glad I posted the previous entry, since the response has caused me to re-evaluate the code I was writing and made me re-implement the type conversion operators as simple "ConvertTo..." methods. Almost as terse, just as intuitive, and no messing with identity.
 
 

Posted Dec 12 2005, 05:40 PM by fritz-onion
Filed under:

Comments

Christopher Steen wrote Link Listing - December 12, 2005
on 12-12-2005 7:09 PM
CLR Profiler and the WebDev Server [Via: scott ]
DHTML IV: Highlighting a table row or column [Via:...
Pedro Felix wrote Blog interaction: a "C# conversion operators" tale
on 12-13-2005 5:07 PM
A first post on the benefits of the usage of C#'s "conversion operator": http://pluralsight.com/blogs/fritz/archive/2005/12/09/17343.aspx...
Dinis Cruz @ Owasp .Net Project wrote FireFox Tab Dump – 14 Dec 2005
on 12-13-2005 6:50 PM

Since FireFox just
stopped responding (i.e. opening up new pages, but at least didn't
die (like it...
Craig (a different one) wrote re: Type conversion operators in C# revisited
on 01-24-2006 9:25 AM
For the example that seems to have convined you, is identity what you'd want to check? I would think you want to check for equality which, in this case, would mean field value equality not reference equality. Requires coding == and != operators and the Equals method to keep it consistent, though. Bertrand's example would work in this case... I think.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?