Having trouble with Lambdas in VB.net

I’m using NSubstitute in a new TDD project for a component. Normally I prefer to program in C# but the company I’m currently working for is a VB-Shop, so I have to use VB here. (Note: I’m using VS 2008 atm)

NSubstitute is a mocking framework which makes heavy use of Lambdas. This results in compact and very readable Tests.

Here is an example where I want to throw an exception when a specific method on a mock is called (C# version). Given this interface:

In the test we expect that the Bar() method should throw an ApplicationException.

First we create a Substitute (a mock) aSub. By using the Returns() – extension method which comes with NSubstitute, it is possible to define what should be returned by a given method. Here I just define that calling Bar() throws the expected ApplicationMethod.

Calling Bar() throws and our test turns green.

Now turning to the ~~dark side ~~VB side:

The first thing to notice here is how VB spoils the nice syntax by the Of Keyword for generics. Substitute For Of IFoo is just not as nice as  Substitute <IFoo>.

But let’s focus on the main part I want to discuss. To satisfy the tests expectations we cannot just use a nice lambda as in C# because throw new ApplicationException just returns nothing, which is not allowed in VB. The workaround is to use a delegate. So let’s point to (AddressOf) our ThrowExForString Function.

To define this function you have to figure out which signature you have to use. This is not as easy as I thought and ReSharper won’t generate the correct signature for you. Studying the NSubstitute sources and the compiler errors is the way to go. Sadly.

In contrast to the C# example we have to deal with internal details to generate the matching method signature just to throw an exception.

To be fair the method could be generalized by using generics:

And the generic method:

Summary: It’s not only NSubstitute which looses the concise syntax. It's all over the place when using Lambdas in VB.net!  I hope Visual Studio 2010 brings some improvements to the language.