tags:

views:

69

answers:

1

Why doesn't this C# typecheck? In this example, I am trying to pass a method of type string -> string as a Func<string, string>. It would be seem perfectly reasonable to be able to omit lambda syntax when passing just the name of an appropriately typed function.

using System;
using System.Linq;

class WeakInference
{
  public static void Main (string [] args)
  {
    // doesn't typecheck
    var hellos = args.Select (AppendHello); 

    // have to do this:
    // var hellos = args.Select (s => AppendHello (s));
  }

  static string AppendHello (string s)
  {
    return s + "hello";
  }
}
+6  A: 

You can using the C# 4 compiler. The C# 3 compiler had weaker type inference around method group conversions. You can read the details in Eric Lippert's answer here. It's not entirely clear to me whether this means that the C# 3 compiler doesn't actually implement the C# 3 spec, or whether the spec itself changed between 3 and 4 in this area. That's a pretty academic question compared with whether or not the compiler does what you want it to ;)

(I've just tested it, and your program doesn't compile with VS 2008, but does compile with VS 2010.)

Jon Skeet
Thank you! This is wonderful news.
David Siegel