As a means of introducing lazy formatting evaluation in a library I am developing, I have defined the delegates
public delegate string MessageFormatterDelegate(string message, params object[] arguments);
public delegate string MessageFormatterCallback(MessageFormatterDelegate formatterDelegate);
and something along the lines of the following class
public static class TestClass
{
public static string Evaluate(MessageFormatterCallback formatterCallback)
{
return (formatterCallback(String.Format));
}
}
However, this is behaving strangely enough: when running from an external project, the statement
Console.WriteLine(TestClass.Evaluate(message => message("{0},{1},{2}", 1, 2, 3)));
does not compile, failing with the error
Error 1 Delegate 'MessageFormatterDelegate' does not take 4 arguments
while
Console.WriteLine(TestClass.Evaluate((MessageFormatterDelegate message) => message("{0},{1},{2}", 1, 2, 3)));
compiles and works with no problems, printing 1,2,3 in the console. Why do I have to qualify the message argument with MessageFormatterDelegate type in the second lambda expression? Is there any way to circunvent this behaviour?
EDIT: Okay, I’ve now got a much shorter example and a workaround.
First source file,
External.cs:Second source file,
Test.cs:Compile with:
Error:
Workaround: change the body of the
Mainmethod to:… or include the delegate declaration in the same assembly which uses it.
This definitely looks like a bug to me. When the compiler knows that the type of
foois a particular delegate type, thenfoo(arg)andfoo.Invoke(arg)should be equivalent.Will mail Eric Lippert…