C
C#3y 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
PollerOP3y ago
Also a point i need to make: i can not change the implemented interfaces in "TestType".. sadly
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Poller
PollerOP3y 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
Thinker3y 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
PollerOP3y ago
can you rephrase the second part? i not understand what you mean with "not being able to be used as a parameter
333fred
333fred3y ago
You cannot have a method with a parameter that is T
Thinker
Thinker3y ago
You can do T Foo(); but not void Foo(T t); If you use out, that is
Poller
PollerOP3y ago
i am gonna test this real quick to see if some of the code is using this
Thinker
Thinker3y ago
IEnumerable<out T> uses this if you're curious, you can cast from IEnumerable<string> to IEnumerable<object>.
Poller
PollerOP3y 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
333fred3y ago
Then you can't do the conversion. It's not safe
Poller
PollerOP3y 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
333fred3y ago
Then you need to come up with another solution Without out, this does not work, because it is not safe
Poller
PollerOP3y ago
yeah... im gonna search. thanks for trying
Tvde1
Tvde13y ago
You could make two separate type parameters, one in and one out, right?
Thinker
Thinker3y ago
That... sounds mildly reasonable...?
Poller
PollerOP3y 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
Tvde13y 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
PollerOP3y 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