Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use implicit casting?

Tags:

c#

.net

casting

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?

like image 994
C. Ross Avatar asked Sep 02 '09 15:09

C. Ross


2 Answers

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).

like image 131
Marcin Deptuła Avatar answered Oct 03 '22 19:10

Marcin Deptuł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...

like image 22
Julian Birch Avatar answered Oct 03 '22 21:10

Julian Birch