Wednesday, September 1, 2010

Why Are My Lambda Functions Throwing An Error at Run Time With a System.MissingMemberException Exception?

Recently I was working in a VS.NET 2010 project and I was creating a multiline Lambda expression function within a method to use. It was pretty straight forward and was syntactically correct. I could build the application successfully, but when hitting that code at compile time I received the following error:

No default member found for type 'VB$AnonymousDelegate_0(Of String,String)'.
System.MissingMemberException occurred
Message=No default member found for type 'VB$AnonymousDelegate_0(Of String,String)'. Source=Microsoft.VisualBasic

The signature of (Of String,String) is not that important and if you are receiving this problem, it would reflect the lambda functions signature of your method. I took the code and placed it in a test harness VS.NET 2010 app, and it both compiled and ran successfully. One thing I immediately noticed is if I hovered over the Function variable declaration it resolved to: Dim MyFormatFunc As <Function(String) As String>. In my problematic application it resolved to nothing.

Well the problem lies in the project setting to allow 'Type Inference'. This was a VS.NET 2005 originating project that has been converted to 2008, then to 2010. If the project originated in 2008 or later, Type Inference is set to 'On' by default. My grandfathered application had it set to 'Off' which meant these anonymous types would be treated as type 'Object' instead of resolving to their appropriate type.

You can change this setting at the page, class, or project level which is what I prefer. To turn on this setting, right-click your project in Solution Explorer within VS.NET (or double click "My Project" to get the same result) which will bring up the project's properties. Click on the 'Compile' tab and change the dropdown for 'Option infer:' from 'Off' to 'On' (pictured below).

Recompile your app and run it again. Your lambda functions will work properly and you will not receive any errors (assuming you coded them correctly to begin with). You will also see the IDE resolves the type at design type if you hover over the declared lambda function variable.

1 comment:

  1. More effective and safer solution is to keep type inference Off and correct actual errors in the code which type inference set to On just worked around. You will see the errors after turning Option Strict On and Option Explicit On.