Sunday, February 05, 2006

 

Type Inference in C#: No Trail Arguments Deduction

Like C++, C# does type inference when a generic function is called:
class Test
{
private static void f< T >( T p ) { }

public static void Main()
{
// explicit type argument
f< int >( 3 ) ;
// type inference
f( 3 ) ;
}
}
According to the C# Version 2.0 Specification, "The presence of type inference allows a more convenient syntax to be used for calling a generic method, and allows the programmer to avoid specifying redundant type information". All so true. Unfortunately, they didn't look close enough to what C++ can do, that is, trail argument deduction.

This is legal C++ :
template< class T1, class T2 > void f( T2 p2 )
{
}

int main()
{
f< double >( 3 ) ; // calls f< double, int >( 3 )
}
but this is not legal C# :
class Test
{
private static void f< T1, T2 >( T2 p ) { }

public static void Main()
{
f< double, int >( 3 ) ; // works
f< double >( 3 ) ; // error
}
}
Why would you want trail argument deduction? For the same reasons you want type inference: to get a more convenient syntax, and to avoid specifying redundant type information. (Of course, in real cases, f would make use of type T1 inside its body; I could definitely use something like that for my GUI rules library [see my post "C#: In search of language"]).
Overall my experience with C# is mixed. There is some good stuff in it. But as soon as you try to do something slightly more advanced, you're hitting a wall. It's so disappointing. Gotta do something about it :-)).

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?