C
C#2y ago
Poller

Cast failing on runtime

I have a construct. that i simplified in a little example seen below. I was wondering how i can resolve the problem on the given cast failing on runtime. i think it should work, but it doesnt.
21 Replies
Poller
Poller2y ago
Also a point i need to make: i can not change the implemented interfaces in "TestType".. sadly
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Poller
Poller2y ago
makes sense to me. but InheritedType contains everything that BaseType is... Is there some workaround i can take to get this converted? (Performance is not an issue. Its usually run once)
Thinker
Thinker2y ago
Make T into out T, that will allow you to cast like you want here Although this limits T to only being able to be returned and not being able to be used as a parameter.
Poller
Poller2y ago
can you rephrase the second part? i not understand what you mean with "not being able to be used as a parameter
333fred
333fred2y ago
You cannot have a method with a parameter that is T
Thinker
Thinker2y ago
You can do T Foo(); but not void Foo(T t); If you use out, that is
Poller
Poller2y ago
i am gonna test this real quick to see if some of the code is using this
Thinker
Thinker2y ago
IEnumerable<out T> uses this if you're curious, you can cast from IEnumerable<string> to IEnumerable<object>.
Poller
Poller2y ago
i just looked into the code. and since this interface implements and inherites others with also my T parameter i cannot use this approach.
333fred
333fred2y ago
Then you can't do the conversion. It's not safe
Poller
Poller2y ago
i control all 3 types of objects that come out of this factory where i have my problems. - 2 types implement ISomeInferface<InheritedType> - 1 type implements ISomeInferface<BaseType> in my usecase i need to use ISomeInterface<BaseType>. but i dont want(not allowed) to change the base types of the 2 impementations that work with the inherited
333fred
333fred2y ago
Then you need to come up with another solution Without out, this does not work, because it is not safe
Poller
Poller2y ago
yeah... im gonna search. thanks for trying
Tvde1
Tvde12y ago
You could make two separate type parameters, one in and one out, right?
Thinker
Thinker2y ago
That... sounds mildly reasonable...?
Poller
Poller2y ago
That sounds not bad. i am just on my way to a meeting with my college who made a lot of the classes here and dependencies. we gonna see.
Tvde1
Tvde12y ago
it's just that I haven't used base and derived classes in a long long time, there has always been a better alternative using composition to not get these problems oh wait my example also fails in runtime
Poller
Poller2y ago
the decision was made. wo use a wrapper to convert the in and outgoing types. (prevents us breaking changes in other dependencies)
Want results from more Discord servers?
Add your server
More Posts