✅ Invalid cast between interface types
Hello. I'm trying to learn functional programming in C#, so I'm ending up with some unusual code. A part of that is having an array of options marked with their length, like so
Since this is so long, I've defined this
This inevitably means casting to FieldUnits at some point, and doing so is giving me this error
I'm not sure why though, since they seem to be the same. I also swear this was working the other day. Any ideas what's wrong here? Here's a sample line that has this problem
18 Replies
they might seem the same, but they are not
FieldUnits is not the same interface
anything that implements FieldUnits is just guaranteed to implement the long one
Right. I figured that meant I could cast them like this. Looking at it I realised I'm not actually casting to an object at all. VS not complaining about it has me a little confused though.
the inverse isn't true though
not everything that implements the long one is guaranteed to implement FieldUnits
Up v down casting, right.
VS doesn't complain because it's possible that the return value implements it
it doesn't know
It doesn't know it's casting to an interface and not an object?
casting to an interface is a valid thing to do
Windows10CE#8553
REPL Result: Success
Compile: 474.880ms | Execution: 33.290ms | React with ❌ to remove this embed.
because C implements both interfaces
you could define aliases with global usings, which only works for .net6+ I think
Ah, that would be perfect. It's what I was trying to do with this.
you won't be able to export them as symbols tho, they would ve purely compile time things and local to the project they are defined in
Ah. That's a shame. Fine in this context, but probably shouldn't get into the habit of it. Is there a way I can get this to cast nicely?
the language is not designed to handle this much generic complexity nicely, so you either have to make your design more dynamic, which is preferable by the design of the language, or have to deal with the noise and unmaintainability of repeating those types
source generators is also a way
I think I crossed that bridge when I started using Language.Ext 😅
in some cases
C# is not happy with me, nor is my use case.
Closed!