3

I need some help translating this code from c# to vb.net:

    private static Action<int, int> TranslateOrigin(Action<int, int> f, int x, int y)
    {
        return (a, b) => f(a + x, b + y);
    }

The automatic translators I've found on the internet make a mess of it, producing:

Private Shared Function TranslateOrigin(f As Action(Of Integer, Integer), x As Integer, y As Integer) As Action(Of Integer, Integer)
    Return Function(a, b) f(a + x, b + y)
End Function

Which won't compile, complaining that "Expression doe not produce a value." I've been poking at it for a while now and haven't had any luck translating it, any help would be greatly appreciated.

1
  • +1 the automatic translators are rubbish at lambdas. Commented Oct 24, 2012 at 5:45

3 Answers 3

4

I think this is a bit closer since it doesn't return a value, but rather an action. using a single line.

Public Shared Function TranslateOrigin(f As Action(Of Integer, Integer), x As Integer, y As Integer) As Action(Of Integer, Integer)
    Return Sub(a, b) f(a + x, b + y)
End Function
Sign up to request clarification or add additional context in comments.

Comments

1

This should do it:

Private Shared Function TranslateOrigin(ByVal f As Action(Of Integer, Integer), ByVal x As Integer, ByVal y As Integer) As Action(Of Integer, Integer)
     Return Function (ByVal a As Integer, ByVal b As Integer) 
               f.Invoke((a + x), (b + y))
            End Function
End Function

Comments

0

You are aware that an Action(Of T1, T2) delegate does not return a value? If it is anyway what you want (though I don't see much of a point in it, with value types), you can use a Sub.

Encapsulates a method that has two parameters and does not return a value.

With a sub, that will give this code:

Private Shared Function TranslateOrigin(f As Action(Of Integer, Integer), x As Integer, y As Integer) As Action(Of Integer, Integer)
    Return Sub(a, b) f(a + x, b + y)
End Function

You probably want to return a value, therefor you'll need a Func(Of T1, T2, TResult) delegate. In your case, that would make:

Private Shared Function TranslateOrigin(f As Func(Of Integer, Integer, Integer), x As Integer, y As Integer) As Func(Of Integer, Integer, Integer)
    Return Function(a, b) f(a + x, b + y)
End Function

Calling it as below, will return the value 6 (as I guess is expected):

TranslateOrigin(Function(x, y) x + y, 1, 2)(1, 2)

Comments

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.