Why are conversions from "class A: IX" to general "T, where T: IX" not allowed?

Why do the following causes a compilation error?

interface IX {} interface IY {} class XY : IX, IY {} void Foo<T>() where T : IX, IY { T xy = new XY(); … // ^^^^^^^^ } // error: "Implicit conversion of type 'XY' to 'T' is not possible." 

Note. . The same error occurs if class XY : IX and where T : IX . However, I chose a more complex example, because a simpler one might provoke workarounds such as: β€œJust change the xy type from T to IX ” which would not answer why this conversion fails.

+6
source share
2 answers

Given class ABC : IX, IY { } and Foo<ABC> , would you expect to be able to use new XY() ? Because you should not have this expectation. The compiler will not be either.

T will not always be XY. T will be ABC, DEF, or anything else that can implement your two interfaces and therefore satisfy the limitations that you have. XY does not convert to ABC, DEF, or any of the infinite possibilities for T, and therefore you have an error message: implicit conversion of XY to T is not possible.

What would be legal is simply new T() , and this is only true if the method is limited to support it.

 void Foo<T>() where T : IX, IY, new() { T obj = new T(); } 
+12
source

Because if it was legal, you could do this:

 interface IPet {} interface IMammal {} class Dog : IPet, IMammal {} class Cat : IPet, IMammal {} T Foo<T>() where T : IPet, IMammal { return new Dog(); } ... Cat cat = Foo<Cat>(); // Assigns a Dog to a variable of type Cat. 
+15
source

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


All Articles