c# - ForEach giving Invalid Cast at Runtime -
i have following:
foreach (itemoption itemoption in p.items.select(e => e.itemoption).groupby(e => e.id)) { // work on itemoptions }
this compiles. @ runtime invalid cast exception:
unable cast object of type 'grouping[system.string,mynamespace.itemoption]' type 'mynamespace.itemoption'.
if change code to, e.g. string type of item :
foreach (string itemoption in p.items.select(e => e.itemoption).groupby(e => e.id)) { // work on itemoptions }
then compiler tells me types incompatible.
why doesn't compiler flag type incompatibility in first code block?
i did further investigation , found that, given following code:
var foo = p.items.select(e => e.itemoption).groupby(e => e.id)); type singleelementtype = foo.elementat(0).gettype();
singleelementtype
is:
system.linq.lookup`2+grouping[system.string, mynamespace.itemoption]
update following on answers have put simpler case demonstrate issue
given objects:
interface imyobj { string id; } class myobj : imyobj { public string id; public myobj2 cg; } class myobj2 { }
this fail @ compile time
ienumerable<myobj> compiletimefaillist = new list<myobj>() foreach (myobj2 myobj2 in compiletimefaillist.where(x => x.id != null)) {
and fail @ run time
ienumerable<imyobj> runtimefaillist = new list<imyobj>(); foreach (myobj2 myobj2 in runtimefaillist.where(x => x.id != null)) {
the reason being objects in runtimefaillist
may extend myobj2 , cannot determined compiler.
itemoption
presumably not sealed class (unlike system.string) it's possible result of p.items.select(...).groupby(...)
implementations of igrouping<...>
also itemoption
values. compiler can't know, inserts implicit cast. string
doesn't implement igrouping<...>
, sealed, compiler can spot that's mistake.
foreach
has always included cast necessary. it's bit nasty, because it's hidden... without it, foreach
have been painful use pre-generics.
now why it's actually wrong... each item in result going grouping rather individual item. let me know if need more working results.
Comments
Post a Comment