tags:

views:

61

answers:

3

Hey guys,
This is a quick one. I have the following code:

foreach (var item in myRepeater.Items)
{
    MyViewModelItem x = new MyViewModelItem();
    MapToEntity(x, item);
    myList.Add(report);
}

void MapToEntity(object entity, Control control);

I expected this code to compile with no problems. It didn't, however.
It resulted in a compile time error saying that the method "MapToEntity" has some invalid arguments. The compiler failed to infer the type of the RepeaterItem, it recognizes it as a plain System.Object.

Why is this happening? Am I missing something?
Ps: I fixed the code by deleting the var keyword and explicitly defining the type of the item "RepeaterItem".

+6  A: 

RepeaterItemCollection does not implement IEnumerable<RepeaterItem> just plain IEnumerable. Thus, it's impossible for the compiler in infer the type.

Anton Gogolev
walkaround would be `Items.OfType<RepeaterItems>()` or `Items.Cast<RepeaterItems>()`
Andreas Niedermair
Aha .. Now, I got it. Thanks Anton!
Galilyou
You should note that .OfType() is "safer" because it will remove any values that are not of the correct type. While .Cast() will throw an exception. Not an issue if you don't have mixed types in your collection.
Matthew Whited
+1  A: 

First, your code sample shows that you are using a variable named "item" in the foreach statement and then declaring one of another type below it.

Second the reason you probably seeing it as type Object is that myRepeater.Items is probably a general collection and not a specifically typed one so it would return of type Object. You can specifically state of what type in the ForEach loop and it will return objects of that type if any exist.

A possible solution would be to do myRepeater.Items.OfType() and then you could use the var keyword.

Adam Gritt
+1  A: 

As Anton said, the Items only implements IEnumerable which is why it cannot infer the type.

One thing that you may find useful though is the Cast method.

myRepeater.Items.Cast<RepeaterItem>()

Whilst your example is simple enough for this to not really be needed it may help for more complex examples where you need a typed enumerable.

Robin Day