Home > Software engineering >  Get List Of Derived Class From Elements Of Base Class List<>
Get List Of Derived Class From Elements Of Base Class List<>

Time:08-15

I have a List of a base class called ItemData

Within this list, I have several elements of a derived class called WeaponData (inherits from base class ItemData)

To clarify, it is a List<'ItemData'> and during runtime I populate that list with derived class objects. For several reasons, I need this List to remain of ItemData type -- I don't wish to change the list type.

I want to get the list elements from List (which is filled with WeaponData) and access the WeaponData properties, adding them to a new separate List<'WeaponData'>

Base Class:

public class ItemData : ScriptableObject
{
    public Sprite Icon;
    public ItemCategory Category;
    public ItemSubCategory SubCategory;
}

Derived Class:

public class WeaponData : ItemData
{
    public WeaponName WeaponName;
    public WeaponScript Script;
    public int CurrentLevel;
    public int MaxLevel;
    public int BaseDamage;
 
}

When retrieving the List items, I need to access them AS their derived class

if (slot.IsFilled)
            {
                // 'weapons' is a List<WeaponData>
                weapons.Add(slot.ItemData); /////////////// CANNOT CONVERT FROM ITEMDATA TO WEAPONDATA
            }

I'm getting the error that I cannot convert the ItemData list element into WeaponData

I don't necessarily want to convert it, I simply want to get it -- it's already WeaponData type but sitting in an ItemData list

CodePudding user response:

I want to get the list elements from List (which is filled with WeaponData) and access the WeaponData properties, adding them to a new separate List<'WeaponData'>

You can accomplish this as follows:

var itemData = new List<ItemData>();
// Initialize itemData

weapons.AddRange(itemData.OfType<WeaponData>()

CodePudding user response:

Fixed with

if (slot.ItemData is WeaponData weaponData)
{
    weapons.add(weaponData);
}
  •  Tags:  
  • c#
  • Related