silentneedle
silentneedle

Reputation: 3

Declare derived class in if/else without repeating base class fields

I'm currently trying to populate a dictionary from data which I receive from a json string.

My current approach:

public class Item {

    public class BaseItem {
        public int id;
        public int level;
    }

    public class Armor : BaseItem {
        public int durability;
    }

    public class Weapon : BaseItem {
        public int damage;
    }
}

foreach (JsonObject jsonObject in jsonArray) {
    if (jsonObject["armor"] != null) {
        var item = new Item.Armor();

        item.durability = jsonObject["armor"]["durability"];
    } else if (jsonObject["weapon"] != null) {
        var item = new Item.Weapon();

        item.damage = jsonObject["weapon"]["damage"];
    } else {
        var item = new Item.BaseItem();
    }

    item.itemID = jsonObject["id"];
    item.level = jsonObject["level"];

    Item.data.Add(item.itemID, item);
}

Unfortunately this doesn't compile because I declare 'item' in the if/else statement.

Is there any way to do this without defining the base class fields for each item type?

Upvotes: 0

Views: 258

Answers (2)

Mark Sowul
Mark Sowul

Reputation: 10610

To build on davisoa's answer, but still not require casts: remember, you can have more than one reference to an object. Yay, polymorphism!

foreach (JsonObject jsonObject in jsonArray) 
{
    Item.BaseItem item;

    if (jsonObject["armor"] != null) 
    {
        Item.Armor armor = new Item.Armor();
        armor.durability = jsonObject["armor"]["durability"];

        item = armor;
    } 
    else if (jsonObject["weapon"] != null) 
    {
        Item.Weapon weapon = new Item.Weapon();
        weapon.damage = jsonObject["weapon"]["damage"];

        item = weapon;
    } 
    else 
    {
        item = new Item.BaseItem();
    }

    item.itemID = jsonObject["id"];
    item.level = jsonObject["level"];

    Item.data.Add(item.itemID, item);
}

Upvotes: 1

davisoa
davisoa

Reputation: 5439

I would declare item outside of your if statements.

foreach (JsonObject jsonObject in jsonArray) {
    Item.BaseItem item;        

    if (jsonObject["armor"] != null) {
        item = new Item.Armor();

        ((Item.Armor)item).durability = jsonObject["armor"]["durability"];
    } else if (jsonObject["weapon"] != null) {
        item = new Item.Weapon();

        ((Item.Weapon)item).damage = jsonObject["weapon"]["damage"];
    } else {
        item = new Item.BaseItem();
    }

    item.itemID = jsonObject["id"];
    item.level = jsonObject["level"];

    Item.data.Add(item.itemID, item);
}

Upvotes: 1

Related Questions