Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuple.Create return type

Given

void foo(Tuple<object> t)
{

}
void bar()
{
    foo(Tuple.Create("hello"));
}

the c# compiler returns

error CS1502: The best overloaded method match for 'foo(System.Tuple<object>)' has some invalid arguments
error CS1503: Argument 1: cannot convert from 'System.Tuple<string>' to 'System.Tuple<object>'

Adding explicit types to Tuple.Create defeats its purpose. How can I convince the compiler to accept the code?

FWIW, I think C++ doesn't have this problem: http://live.boost.org/doc/libs/1_33_1/libs/tuple/doc/tuple_users_guide.html#constructing_tuples

like image 475
Bruno Martinez Avatar asked Jun 07 '26 22:06

Bruno Martinez


1 Answers

This is the same generic type covariance issue that comes up daily. It is simply not possible to convert Foo<T> to Foo<SubT> or vice-versa. Starting with .NET 4, it is supported - but only for interfaces and delegates, and by explicitly specifying the generic type parameter as variant by declaring it Foo<out T1>.

like image 102
Rex M Avatar answered Jun 10 '26 13:06

Rex M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!