Help using generics and maps
I've been trying to make a basic listener consumer system for a Minecraft server implementation im making in c# from scratch. I come from a java background so c# is fairly similar but im stuck on trying to make a generic map of an unknown type at runtime.
I'm trying to rewrite this to c#.
I have
Any help would be fantastic, thank you :D
19 Replies
Please ping me if anyone replies
Can't you just use the interface instead of a generic parameter even in the
listener
?
Thing with Java is that generics are fake and don't exist during runtime, they just get replaced with an Object
and a bunch of casts
C# does not erase generics, so it's a bit more strict
Stuff like type covariance/contravariance come into playI could but then i'd need to define a class extending it at all times since Functional interfaces dont exist and c# has deligates instead
Most of the listeners i need are one/two liners so it'd be a lot of unnecessary boilerplate
But if that's my only alternative ig
Worst case scenario, use
object
and validate that it's of that interface ¯\_(ツ)_/¯wdym
Angius
REPL Result: Success
Console Output
Compile: 473.945ms | Execution: 39.387ms | React with ❌ to remove this embed.
You can use pattern matching to check that an
object
is an IFoo
and cast it to an IFoo
in one go
This is more like what Java would do under the hoodyeah but im not sure how that would help my case
you cant also put unknown generics into c# collections either so i couldnt convert it to an interface
unless u mean i make it store the object type then cast it
Ah yeah LOL
Still seems like a very hacky workaround
And the listener would be, say,
I got it
that's rather annoying
but nothing i cando
Thank you for your help :D
It's about the only thing I could think of, maybe someone else will have a better solution
I'll do it for now and see if i can find a better fix down the line
Maybe covariant/contravariant generics would help here, idk
Making the
T
an in
or out
generic, etcI'd need to look into how that works in c#
I'll be honest, I don't fully understand co/contravariance myself lol
I remember the concept from kotlin but its still mad hacky LOL