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
Also a point i need to make: i can not change the implemented interfaces in "TestType".. sadly
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
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)
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.can you rephrase the second part? i not understand what you mean with "not being able to be used as a parameter
You cannot have a method with a parameter that is T
You can do
T Foo();
but not void Foo(T t);
If you use out
, that isi am gonna test this real quick to see if some of the code is using this
IEnumerable<out T>
uses this if you're curious, you can cast from IEnumerable<string>
to IEnumerable<object>
.i just looked into the code. and since this interface implements and inherites others with also my T parameter i cannot use this approach.
Then you can't do the conversion. It's not safe
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
Then you need to come up with another solution
Without out, this does not work, because it is not safe
yeah...
im gonna search. thanks for trying
You could make two separate type parameters, one in and one out, right?
That... sounds mildly reasonable...?
SharpLab
C#/VB/F# compiler playground.
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.
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
the decision was made. wo use a wrapper to convert the in and outgoing types. (prevents us breaking changes in other dependencies)