Jun Kang
Jun Kang

Reputation: 1275

Converting C# Lambda to VB.NET

I'm trying to convert the following C# code to VB.NET. The issue is with the lambda expression.

public class UserStore
{
    private readonly IDatabaseFactory _databaseFactory;

    private DataContext _db;
    protected DataContext Db => _db ?? (_db = _databaseFactory.GetDataContext());

    public UserStore(IDatabaseFactory databaseFactory)
    {
        _databaseFactory = databaseFactory;
    }
}

The following is what I've converted the code to:

Public Class UserStore
    Private ReadOnly _databaseFactory As IDatabaseFactory

    Private _db As DataContext
    Protected Db As DataContext = Function() As DataContext
                                     If _db Is Nothing Then
                                         _db = _databaseFactory.GetDataContext()
                                     End If
                                     Return _db
                                  End Function

    Public Sub New(databaseFactory As IDatabaseFactory)
        _databaseFactory = databaseFactory
    End Sub
End Class

For some reason, the converted lambda gives the error Lambda expression cannot be converted to 'DataContext' because 'DataContext' is not a delegate type.

Can anybody tell me what I'm doing wrong here?

Upvotes: 0

Views: 427

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660493

I'm trying to convert the following C# code to VB.NET. The issue is with the lambda expression.

The issue is that you've mistaken an expression-bodied property for a lambda.

In C#

protected DataContext Db => _db ?? (_db = _databaseFactory.GetDataContext());

is a short way of writing

protected DataContext Db { 
  get 
  {
    return _db ?? (_db = _databaseFactory.GetDataContext());
  }
}

It's not a lambda at all; if you want to translate this to VB, just write a normal VB property getter.

Note that C# allows you to do this trick with methods as well:

public Abc Foo(Bar bar) => Blah(bar);

is just a short way of writing

public Abc Foo(Bar bar) 
{
  return Blah(bar);
}

Upvotes: 9

Related Questions