tags:

views:

166

answers:

2

When is it safe to use implicit casting?

Use Case: I'm working with a set of com objects that need to be taken care of specially (Marshal.ReleaseComObject). Is it OK to create a wrapper class that implicitly converts back to the actual com object wrapped?

What are some situations when I shouldn't use implicit casting?

+4  A: 

You should use implicit casting when (and only when) you are sure that:
1. No information (data) is lost (or can be lost) while converting.
2. No exception can be thrown.
3. No silent fail can occur (you will receive degenerated data).

Ravadre
+1  A: 
  1. You need to perform this cast a lot.
  2. There isn't a way to avoid the cast.
  3. It's not better represented as a conversion/projection function. To put it another way, it's got to be "the same object" after the cast.
  4. You can round-trip to the original object. (Not implicitly, though.)
  5. It's not going to mess with existing or possible future function overloads.

I usually summarize these points as "never", but ironically your use case actually sounds like a goer...

Julian Birch