From MSDN:
By eliminating unnecessary casts, implicit conversions can improve source code readability. However, because implicit conversions can occur without the programmer's specifying them, 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 used safely without the programmer's awareness. If a conversion operator cannot meet those criteria, it should be marked explicit.
While I don't disagree with any particular point, and I agree that this is all very good, is there ever a reason that is great enough to warrant breaking the part about implicit conversions not throwing exceptions?
The particular case I have before me is one where:
- I have a function, which returns a custom collection object (we'll call it
FooCollection
). - This function can return collections with a single item, and it can be determined from the source code whether this will happen or not. (by this I mean just the function call, not the function itself)
- If it does happen, it is 99.9% likely that the user wants that single item, rather than a collection with a single item.
Now, I'm tossing up whether to include an implicit conversion from FooCollection
=> Foo
to hide this little implementation detail, but this conversion will only work if there is a single item in the collection.
Is it ok to throw an Exception
in this case? Or should I be using an explicit cast instead? Any other ideas about how I could deal with this (no, due to implementation details I can't just use two functions)?
EDIT: I feel it worthy of noting that FooCollection
doesn't implement any interfaces or actually extend Collection
as the name might imply, hence the LINQ based answers are useless. Also, while the collection does implement a numeric index, it isn't the most intuitive way of dealing with the collection as it relies on named index mostly.