change return type of virtual method

Hey, I have a Database which contains every item in the game.

I have a base class Item

        public class Item: ScriptableObject 
        {
        private string itemName;
        public virtual Item ReturnItem() 
        {
            return this;
        }
        }

Several classes like Weapon derive from Item.

            public class Weapon: Item
            {
            private int damage;
            public override Item ReturnItem() 
            {
                return this;
            }
            }

Is it possible to make the override method ReturnItem return the childclass(Weapon) instead of just the item?

Or is there any other way to determine what childclass the Item belongs to aside from casting it to a weapon and checking if it threw a error

That’s not possible, but you can know which type it is:

List<Item> items = new List<Item>();
items.Add(new Weapon());
items.Add(new Item());

foreach (var item in items)
{
    Debug.Log(item.GetType().Name);
}

If you made Item an abstract class you could do something like this instead:

public abstract class Item
{
    public virtual T GetItem<T>()
    {
        if (GetType() == typeof(T))
            return (T)Convert.ChangeType(this, typeof(T));
        return default(T);
    }
}

and then you could use it like this without having to overwrite the method in other classes (still optional thats why I left it virtual):

List<Item> items = new List<Item>
{
    new Weapon(),
    new Potion()
};

for (int i=0; i < items.Count; i++)
{
    var potion = items*.GetItem<Potion>();*

if (potion == null) continue;
Console.WriteLine(“Item at index " + i + " is a potion!”);
}
This way you get the potion object as a potion type aswel.