Geeks With Blogs
New Things I Learned

One of the nice things with lambda expression is type inference - it is actually pretty neat.  A neat example that is as follows:

private void Test()

{

   string original = "Muljadi";

   string upper = Demo(original, s => s.ToUpper());

   int length = Demo(original, s => s.Length);

}

 

private static TResult Demo<T, TResult>(T value, Func<T, TResult> func)

{

   return func(value);

}

In the example above, the first call to the Demo method has first parameter being a string - which then is immediately inferred to type T.  The compiler will also then infer that the second parameter is a lambda expression, which expects a single parameter, also of type T (which it has recognized as a string), walks thru the lambda expression and recognizes that it returns also a string.  As such, it determines that the first Demo method call will return a string and infer TResult as string.

The second call to the Demo method follows the same path, and again when parsing the lambda expression, it will determine that it returns string.Length, which is of type int - it will then infer TResult as int.

However, I found out that the type inference doesn't work as nicely with actual methods.  The snippet below wouldn't work - I tried with as many combinations as possible, and I could not get it to work without actually creating an instance of the delegate.

private void Test()

{

   string original = "Muljadi";

   int length = Demo(original, GetLength); // Type can't be inferred error

   length = Demo<string, int>(original, GetLength);

   length = Demo(original, new Func<string, int>(GetLength));

   length = Demo(original, s => GetLength(s));

}

 

private int GetLength(string s)

{

   return s.Length;

}

In my mind it just doesn't seem to make sense - the GetLength method is non-generic, has the return types and parameter type in the method and the compiler can't make sense of it.  The other 3 calls are valid because:

  1. You specify the type in the Demo method call itself
  2. Your instantiate the method as a Func delegate, where you also specify the types
  3. You actually make it as a lambda expression call
In the end, lambda expressions actually has better inference support than actual methods.  Hopefully Microsoft can add this in .NET 4.0. Posted on Wednesday, February 13, 2008 6:47 PM .NET | Back to top


Comments on this post: Lambda Expression type inference doesn't quite work on actual methods

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Muljadi Budiman | Powered by: GeeksWithBlogs.net