I have this:
public IClub GetTeam()
{
return new Arsenal();
}
//compiles since Arsenal is an IClub
public T GetTeam<T>() where T : IClub, new()
{
return new Arsenal();
}
//wouldn't compile saying "cannot convert Arsenal to T"
But these things work:
public T GetTeam<T>() where T : IClub, new()
{
T t = new T();
t.Sponsor = "Nike"; //since it knows T is IClub,
return new T(); //but why the injustice to return type alone?
}
Why wouldn't the second code block compile even though return type is anyway
IClub? Isn't that injustice?I know I am not fully utilizing the potential of type constraints in above code but what is an alternative to get the code running?
It's because at compile time the compiler does not know whether
Arsenalwill be convertible toT.Tcould be another type implementingIClubafter all. like inGetTeam<WhateverTeam>().WhateverTeamimplementsIClub, but you cannot convertArsenalto that.You'd have to cast the result if you want your code to compile (as in Marc-André's answer), but you should rather rethink your design (also calling
GetTeam<WhateverTeam>()would result in an exception). Making that method generic doesn't make sense if you already know which type you will return.