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:
FooCollection
).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.
10.2.An implicit dynamic conversion exists from an expression of type dynamic to any type T .
Implicit conversions are evil, for several reasons. They make it hard to see what goes on in code. For instance, they might hide bad surprises like side effects or complex computations without any trace in the source code.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
I'm with the guidelines: You shouldn't ever throw from an implicit conversion.
I definitely wouldn't provide an implicit conversion in this case. Even the idea of an explicit cast feels wrong to me: Foo x = (Foo)fooCollection
just doesn't seem right.
Why don't you just let the calling code worry about the conversion from FooCollection
to Foo
? The code would be much more intuitive for everyone:
Foo a = fooCollection[0];
Foo b = fooCollection.First();
Foo c = fooCollection.FirstOrDefault();
// etc
It clearly is not OK. Never ever use exceptions to implement logic!
You may use the Linq-Statement FooCollection.FirstOrDefault()
, which will give null or the first item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With