smark91 smark91 - 4 months ago 8
C# Question

What's the best way of instance a variable of same name but different type based on switch result

Obviously the following code is wrong because of multiple declarations of compareItem variable.
But for the sake of understanding this is how I want this code work.

switch (objectType)
{
case "Armor":
Item compareItem = player.armor;
break;
case "Shield":
Item compareItem = player.shield;
break;
case "Medikit":
Item compareItem = player.medikit;
break;
case "Grenade":
Item compareItem = player.grenade;
break;
case "Weapon":
Item[] compareItem = player.weapons;
break;
case "Bullet":
Item [] compareItem = player.bullets;
break;
default:
return;
}


What is the best way to make possible instantiate compareItem like a Item class or an array of Item class based on the result of the switch?

Answer

You could use one variable. Since you use Item[] and Item you could use one Item[] for both. In case of armor, shield, medikit and grenade it contains only one item:

Item[] compareItems = null;
switch (objectType)
{
    case "Armor":
        compareItems = new Item[]{ player.armor };
        break;
    case "Shield":
        compareItems = new Item[]{ player.shield };
        break;
    case "Medikit":
        compareItems = new Item[]{ player.medikit };
        break;
    case "Grenade":
        compareItems = new Item[]{ player.grenade};
        break;
    case "Weapon":
        compareItems = player.weapons;
        break;
    case "Bullet":
        compareItems = player.bullets;
        break;
    default:
        return;
}

Your logic must handle the array anyway.