How come this works??

class Base {}

class Item : Base {
public int myvariable;
}

some class {
list mylist;
mylist.Add(Item item1);
mylist.Add(Item item2);
item1.myvariable = some value; //doesnt work because list is of base type
((Item)mylist[1]).myvariable = some value; //this works when i cast but the list is of base type
}

Although both items were of Item type, why do i need casting to make it work?
How come they were added to the list in the first place anyways?

This thing works and ive no problem, but i need to know why it works.

EDIT: Although this works, ScriptableObject doesnt serialize myvariable.
But XML serializes it.

Because you store Base objects in your list and if you access them through the list, it basically returns the Base object (which doesn’t have a variable called “myvariable”). Casting it from the Base object to the Item object gives you access to the variable. But pay attention though: If you store a object that is derived from Base but not Item (ie. class FooClass : Base), the cast will throw a type exception (since the derived class is not convertible to Item).

I see, but isnt this up casting now? I thought it was not possible.

Anyhow, thanks for clarification.

Technically it’s not upcasting because the item is of type Item. If the item was of type Base explicitly then a cast to Item would fail.