mtntrailrunner
mtntrailrunner

Reputation: 761

How do I get the type of an object passed though a generic method to use with foreach?

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();
        }
    }

Upvotes: 0

Views: 86

Answers (2)

Tim Copenhaver
Tim Copenhaver

Reputation: 3302

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
}

Upvotes: 1

Tom Chantler
Tom Chantler

Reputation: 14951

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();
    }
}

Upvotes: 1

Related Questions