Strange generic type behavior

Please check out the simple code below.

public class A{}

  public class B: A{}

  public class G<T> where T : A
  {
    public T GetT()
    {
      return new A();
    }
  }

This code is incorrect - compiler error "Unable to convert A to return type T". But A is actually T. If I change

return new A(); 

to

 return new A() as T;

everything is fine. What is the reason for this behavior? thanks in advance

UPD: An error occurred in the initial question. Now fixed

+3
source share
4 answers

Revised response based on update

Although there Ais a general limitation where T : A, it is a specific type. However, your generic class method GetT()has a generic return type T, so you need to point your specific type to your generic type in order to make return compatibility.

new B().


, T A; , , T B ( ), B A .

, (B B, T B), .

+5

, , :

public class C : A{}

G<C> x = new G();
C c = x.GetT();

B...

as , null, T B A... , , , .

, , , .

+6

,

public class Animal{}

public class G<T> where T : Animal
{
     public T GetT()
     {
       return new Animal();
     }
}

Fish fish = new G<Fish>().GetT();

GetT() Fish, "Animal". : , . , , .

+1

where T : A , T A. T A, B, C A, a B C.

0

All Articles