Clonkex
✅ Return List<Entity> from method with return type of List<T> where T : Entity
you can't expect the compiler to allow you to return a list that has the possibility to contain FootBallEntity instancesOh... yeah... that's super obvious. Idk why I didn't realise that immediately. Thanks
55 replies
✅ Return List<Entity> from method with return type of List<T> where T : Entity
I guess I just assumed the compiler would treat
T
as being Entity
since that's the constraint. But I also don't really know how generic methods are compiled. So using this as the example:
...in my mind, T
is known to be Entity
, and BeachBallEntity
is known to be Entity
, so why am I not allowed to assign a reference to an instance of BeachBallEntity
to a variable of type T
?
But then, you mention function calls for casting and I don't know why that would be necessary either. It seems like the cast to T
could be entirely compiletime. Casting doesn't actually change the data (I assume?), it just changes what you're allowed to do with it. It seems the compiler wouldn't have to actually do anything.
On the other hand there are obviously there are some casts that have to be runtime ((T)(object)new BeachBallEntity();
, for instance). Hmm. This is quite unintuitive to me.
Ultimately it's not important, I just wanted to understand why I wasn't allowed to return List<Entity>
in a method with a return type of List<T> where T : Entity
because it surprised me.
Thanks for trying to explain it seems to be glancing off my smooth brain lol55 replies
✅ Return List<Entity> from method with return type of List<T> where T : Entity
So I didn't realise this (assume
BeachBallEntity : Entity
):
I'm not really sure why this is. Even if T
is MoreSpecificBeachBallEntity
, it's generic, so it's not like I can try to call methods that would only exist for MoreSpecificBeachBallEntity
, for instance. T
is only known to be Entity
so it should be safe to cast any subclass of Entity
to T
, should it not?55 replies