0

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?

1
  • 2
    It is not lambda. It is expression bodied property. Commented Jul 5, 2017 at 20:34

1 Answer 1

9

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was unaware of that. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.