Unlimited listing

My situation:

interface ISomeInterface { void DoSmth<T>(T other); } class Base : ISomeInterface { public virtual void DoSmth<T>(T other){ // for example do nothing } } class Derived<T2> : Base { Action<T2> MyAction {get;set;} public override void DoSmth<T>(T other){ if(typeof(T2).IsAssignableFrom(typeof(T))) MyAction((T2) other); } } 

This gives me an error: Cannot cast expression of type 'T' to type 'T2' (or Cannot convert type 'T' to 'T2' )

I understand that this is due to the fact that neither T nor T2 is limited to a class , but if I know - due to IsAssignableFrom - that I can use T, where I need T2, how can I convince the compiler to allow it?

+6
source share
1 answer

The compiler sees the identifiers T2 and T and informs you that these types seem to be unrelated. This is absolutely correct, since they have nothing to do: there are no general restrictions that would affirm any relationship between them (I am not saying that it would be useful here, though :)).

Whether this is a good feature or not is controversial. Sometimes I would like it to be just a warning, but in most cases it is useful if it was a compilation error. The number of such castings in the birth classes is much less than the number of typos in the "normal" code :)

The solution is very simple. Just trick the compiler to know nothing about the source type, and it will skip checking the type hierarchy with the destination type:

 T theTee = ...; object temp = (object)theTee; T2 teeTwo = (T2)temp; // ok! 'temp' is now seen as 'object' 

or in one insert:

 T2 teeTwo = (T2)(object)theTee; 

Similarly, you can use dynamic (if available in your .Net version):

 T theTee = ...; dynamic temp = theTee; T2 teeTwo = temp; 

and oneliner should work too:

 T2 teeTwo = (dynamic)theTee; 

although I have never tried this since I think it is heavier than the cast-through-object method. However, I did not test the performance of object-dynamic approaches. Just a hunch.

+3
source

Source: https://habr.com/ru/post/989515/


All Articles