0

With the following code I'm trying to pass in 'CachedModel model' which has a list of items List<CachedModel.CachedModelItem>. However the foreach doesn't like 'Item'. Nor does it like Item.GetType() or Type myType = Item.GetType(); foreach(myType item ...

Error is: "The type or namespace name 'Item' could not be found (are you missing a using directive or an assembly reference?)"

Any ideas?

Call:

FillCache<CachedModel.CachedModelItem>(model, CachedEntitiesID);

Method:

public void FillCache<cachedModelItem>(ICachedModel model, int CachedEntitiesID)
        where cachedModelItem: ICachedModelItem, new()
    {
        ICachedModelItem Item = new cachedModelItem();

        foreach (Item item in model.Items)
        {
            string foo = item.foo.ToString();
        }
    }
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
mtntrailrunner
  • 761
  • 6
  • 11

2 Answers2

1

I'm not 100% sure, but if you are saying that Item is of type ICachedModelItem then try changing the method to this:

public void FillCache<cachedModelItem>(ICachedModel model, int CachedEntitiesID)
        where cachedModelItem: ICachedModelItem, new()
{
    foreach (ICachedModelItem item in model.Items)
    {
        string foo = item.foo.ToString();
    }
}
Tom Chantler
  • 14,753
  • 4
  • 48
  • 53
1

More importantly, you don't have to know. Let the compiler figure it out with the var keyword:

foreach (var item in model.Items)
{
    // Do something
}

EDIT: I'm not entirely sure what you're asking, but it may be that you're looking for the .Cast or .OfType extension methods from LINQ. Use Cast if you're sure that all items in the list are actually of the type you're giving it. Use OfType if some items may not match. For example:

foreach (var item in model.Items.OfType<MyType>())
{
    // Do something
}
Tim Copenhaver
  • 3,282
  • 13
  • 18
  • var works but ICachedModelItem has no properties defined so item does not contain a definition for 'foo' – mtntrailrunner Nov 26 '12 at 17:45
  • You haven't told us what the type really is. Your Items collection is clearly of type ICachedModelItem. If that's not the type you need, you'll have to tell us (and the compiler) what type you really want. – Tim Copenhaver Nov 26 '12 at 21:22