Kevin
Kevin

Reputation: 4848

Calling a method of an object that resides within a dictionary?

I have a dictionary that contains an int and an object of type Resource. The Resource object contains a method called CreateNode(). If I write a foreach loop like this:

foreach (var resourcePair in ResourceDictionary)
{
    // call CreateNode() on each Resource object in dictionary pair
}

How can I call the CreateNode() method on each Resource object in the dictionary? I've tried the following, but the editor doesn't like it (says "Cannot resolve symbol"). Which is correct since it appears I'm trying to call the CreateNode method on the pair instead of the CreateNode() method on the object that is part of the pair.

foreach (var resourcePair in ResourceDictionary)
{
    resourcePair.CreateNode(ref xElement);
}

I just can't figure out how to do this. Can someone offer a pointer in the right direction?

Upvotes: 1

Views: 153

Answers (2)

BenM
BenM

Reputation: 4278

You need to do the following:

foreach (var resourcePair in ResourceDictionary.Values)
{
    resourcePair.CreateNode(ref xElement);
}

You need to specify that you want to access the values (which is your collection of resource objects) otherwise you are just accessing a KeyValuePair that doesnt have a CreateNode method.

Upvotes: 4

Alberto
Alberto

Reputation: 15941

resourcePair is a KeyValuePair<Tkey,TValue> in your case KeyValuePair<int,Resource>

so you need to access the Value property in order to call your method:

foreach (var resourcePair in ResourceDictionary)
{
    resourcePair.Value.CreateNode(ref xElement);
}

Upvotes: 2

Related Questions