C# - Loading resources and casting custom classes

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By dinotope

Hello. Brand new to Godot but I work with .Net at my day job so I’m trying to learn the engine with C#. I’m having trouble dealing with custom classes derived from Godot built-in classes. Example:

using Godot;
using System;

public class Item : Resource
{
    [Export]
    public String name = "";

    [Export]
    public Texture texture;
}

My Item class inherits from Godot’s Resource class and adds two props. Elsewhere I am trying to load Resource objects and convert them to my Item:

[Export]
public List<Item> items = new List<Item>(new Item[9]); // Invalid cast error
items[itemIndex] = item;
        
public Item SetItem(int itemIndex, Item item)
  {
        var previousItem = items[itemIndex] as Item; // Invalid cast error
        items[itemIndex] = item;
        List<int> itemIndexList = new List<int>();
        itemIndexList.Add(itemIndex);
        EmitSignal(nameof(ItemsChanged), itemIndexList);
        
        return previousItem;
   }

When using the ResourceLoader.Load() method, my objects come back as Resources, specifically TextureStreams. I get that casting from Resource to Item (Parent to Child) is invalid for C#, but seems the standard in all the GDScript examples. What’s the intended way to work around this strictness in C# with Godot’s native types?

:bust_in_silhouette: Reply From: juppi

Hello dinotope,

yeah, forget about inheritance for resources!

Better Create a Class and add the resource as property:

using Godot;

public class Item
{
    public Texture Texture { get; set; }
    public string Name { get; set; }
}
var item = new Item { Texture = GD.Load<Texture>("res://icon.png"), Name = "icon" };