c# - Is there a workaround for value types making generic inference impossible? -


with method defined below:

public class foo<t1> {     public void bar<t2>(iqux<ibaz<t1, t2>> baz) { } }  public interface ibaz<t1, t2> { }  public struct baz : ibaz<sometype, anothertype> { }  public interface iqux<out t> {}  public class qux<t> : iqux<t> {} 

it apparently impossible have bar infer t2 anothertype when calling so:

new foo<sometype>().bar(new qux<baz>()); 

this work if baz not struct. there workaround when can preserve passing baz value able infer type in such scenario?

it not generic type inference issue, generic variance issue. bar can not infer t2 anothertype because not valid.

new foo<sometype>().bar<anothertype>(new qux<baz>()); 

this call not valid because qux<baz> not implement iqux<ibaz<sometype,anothertype>> interface, bar method requires. iqux<baz> can not casted iqux<ibaz<sometype,anothertype>> because generic variance not supported value-types.

to make call valid, need add additional generic parameter bar method:

public class foo<t1> {     public void bar<t2,tbaz>(iqux<tbaz> baz) tbaz:ibaz<t1,t2> { } } 

although make call valid:

new foo<sometype>().bar<anothertype,baz>(new qux<baz>()); 

it not make generic type inference possible here.


Comments