A few quick questions about Items

vreference
edited August 2011 in DotNet
      public void AddItem(Item item)
        {
            Dictionary<string, Item> typedItems;
            if (this.Items.TryGetValue(item.Type, out typedItems) == false)
            {
                typedItems = new Dictionary<string, Item>();
                this.Items.Add(item.Type, typedItems);
            }

            typedItems.Add(item.Id, item);
            this.listener.OnItemAdded(this, item);
        }

I'm getting close to having a pretty good understanding of most aspects of the MMO client and server (getting very excited about interfacing the server with a database) but I've been looking at this for a while now (from the client PeerListener) and I just thought I would ask... Is it me or does this code never actually add the item to the itemcache (via the Items property) dictionary if it doesn't find an item of that type already existing? Is this an error? It looks like no items would ever get added to the dictionary; as far as I know its the contents of that dictionary that are used to remove the Item objects. Or have I missed something? Also, just curious - This TryGetValue is trying to read from a Property that only has a Get accessor. I wouldn't have guess that world work?

Also (more), just so I understand the thinking behind this, I gather the itemcache is organized by itemTypes to save trygetvalue from searching a sea of Strings? Any thoughts on bestpractice for ID generation? I've never had to work with String IDs! :oops:

Comments

  • :)

    You are misinterpreting this a bit. I didn't write this but understand it this way:
    Per Type, there is a typedItems Dictionary, which contains IDs and the item. One such Dictionary per Type is allowed and aggregated in this.Items.
    this.Items in turn is another Dictionary<Type, Dictionary<string, Item>>. So it contains the Dictionaries per Type.

    TryGetValue tries to find the "item list" matching for the corresponding Type. If it doesn't find such a list, it's created and added to the Dictionary Items.
    If that "item list" of a Type is found, then it's known and put into typedItems. That's the "out" keyword doing in the TryGetValue() call.

    In any case, the typedItems is found after this block and can be used. Then the item is put into it's typed Dictionary of items with it's ID as key.


    You can create GUIDs and turn them into Strings without problem. Or use numbers and make them Strings. Generate either and cast them.
  • I see it now, thanks.