From MSDN :
By eliminating unnecessary casts, implicit conversions can improve the readability of source code. However, since implicit conversions may occur without instructions from programmers, care must be taken to prevent unpleasant surprises. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be safely used without the knowledge of the programmer. If the conversion operator cannot fulfill these criteria, it must be explicitly marked.
While I disagree with any particular point, and I agree that all this is very good, is there a reason that is large enough to justify the violation of some implicit transformations without throwing exceptions?
A special case that I have is one where:
- I have a function that returns a custom collection object (we will call it
FooCollection ). - This function can return collections with a single element, or it can be determined from the source code whether this will happen or not . (by this I mean only calling the function, not the function itself)
- If this is true, then it is a 99.9% chance that the user will want one item, not a collection with one item.
Now I throw up whether to include the implicit conversion from FooCollection => Foo to hide this small implementation detail, but this conversion will only work if there is one element in the collection.
Is it possible to throw an Exception in this case? Or should I use explicit conversion instead? Any other ideas on how I can handle this (no, due to implementation details I can't just use two functions)?
EDIT: I find it worth noting that FooCollection does not implement any interfaces or actually extends Collection , as the name might imply, so LINQ-based answers are useless. In addition, although a collection does implement a numerical index, it is not the most intuitive way to work with a collection, since it mainly uses a named index.
casting explicit c # implicit
Matthew scharley
source share