invalid cast on base class

i’m not sure if this has been asked before or not. i tried to search, but to be honest, i’m not sure what it is that i’m searching for. polymorphism? inheritance? casting?

if you will please excuse the question, i’ll ask it here. if it’s already been asked/answered, by all means throw me a bone and tell me where i need to go or what to search for.

i have a non unity c# base class: Buffer. i then have 2 different classes that derive from Buffer, Wave and Sample. the Wave implements things that pertain to sine, sigmoid etc etc, whereas a Sample pertains to functionality that deals with a wav file: duration, sample rate etc…

in c++ or c# native i can cast between them thusly: ((Sample)buffer) && ((Wave)buffer) since they’re both deriving from Buffer, however in unity, i get an invalid cast?

what gives? is it a mono limitation or something?

.NET is a different animal than C++. It’s really true inheritance so you can only cast within the same inheritance chain. You can cast Sample to Buffer and you can cast Wave to Buffer but you can’t cast Sample to Wave because, while they derive from the same type, they are two different branches and thus two entirely separate types.

Another thing to note… if you’re trying to cast between Sample and Buffer… you’re probably doing it wrong. There shouldn’t be any reason to have to cast between those types. If you need to check to see if it’s a specific type you could do so:

if(typeof(buffer).IsAssignableFrom(typeof(Sample)))
{
   ((Sample)buffer).DoSomeSampleStuff();
}

Why is it you’d want the two types to cast to eachother?

i explained it incorrectly, my apologies. It was ultimately just a bad cast. The issue that was throwing me was that it was failing silently in unity. I re-verified my flow and inputs and found it. Thanks.