0

I'm trying to implement a tile-based platforming system for a 2D game demo from this C++ code into C#,

This is what I have written, It doesn't compile though due to the var variable usage.

 class GameLogic
{
    // Level storage
    String sLevel;
    int nLevelWidth;
    int nLevelHeight;

    // Player Properties
    float fPlayerPosX = 1.0f;
    float fPlayerPosY = 1.0f;
    float fPlayerVelX = 0.0f;
    float fPlayerVelY = 0.0f;
    bool bPlayerOnGround = false;

    // Camera properties
    float fCameraPosX = 0.0f;
    float fCameraPosY = 0.0f;

    public GameLogic()
    {
         var GetTile = (ref int x, ref int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        var SetTile = (ref int x, ref int y, string c)=>                
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };

    }
}

What do you suggest I should do here, to implement this functionality. Thank you for your time.

5
  • why are you using "ref" here? do you expect GetTile to modify the coordinates?
    – IMil
    Feb 14, 2020 at 6:35
  • The original code from the c++ link is using ref variables. I have yet to test it so I'm not sure if it's necessary as I'm still learning the code. @IMil Feb 14, 2020 at 6:37
  • 1
    at a quick glance, you can implement GetTitle/SetTitle as ordinary methods without any magic incantations
    – IMil
    Feb 14, 2020 at 6:40
  • You have an important misunderstanding about the meaning of "capture by reference" in C++ as it relates to C#. C# automatically captures outer locals "by reference" -- that is, it captures variables and not values of variables. Moreover, the variables captured are the outer variables, not the formal parameters of the lambda! Make sure you understand this distinction before you proceed; it is important to get this right. Feb 14, 2020 at 18:46
  • To expand upon @IMil's comment above: you can make GetTile and SetTile local functions in new versions of C#; again, the compiler will take care of ensuring that outer locals of local functions are captured appropriately. C# does not have a facility for "capture by value" like C++ does. (There are rare cases where values are captured instead of variables but you are not likely to run into them.) Feb 14, 2020 at 18:49

4 Answers 4

3

It doesn´t compile because of the var statement. When you use LambdaExpressions and you want to save it to a variable you have to define the delegate Type. But you can´t use ref variables here. But that is ok, because you don´t change the value of x or y.

You need a Delegate that describes the type of your function. You could build you own delegate type but in C# there are two built in types for that case.
Action & Action<T1-16> -> always returns void
Func<T1-17> you can define the return type

The GetTile function takes two int and returns a string.
So you can use Func<int, int, string>.
The SetTitle function has one string parameter more but no return type.
That would be Action<int, int, string>.

internal class GameObject
{
    private int nLevelWidth;
    private int nLevelHeight;

    public GameLogic()
    {
        Func<int, int, string> GetTile = (int x, int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        Action<int, int, string> SetTile = (int x, int y, string c)=>                
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };
    }
}

That´s a good article about delegates.

1
  • Thank you for the detailed explanation and resources :) Feb 14, 2020 at 6:32
2

As other answers have correctly noted:

  • You can't use var with a lambda in C# because the type is ambiguous. You have to state the delegate type explicitly.
  • Your use of ref indicates that you have misunderstood how outer variable capture works in both C++ and C#. You don't need to make these ref, and the outer variables will be captured automatically.

However none of the answers given so far have told you the better solution to this problem, which is to not use lambdas at all! Just use a local function.

public GameLogic()
{
    ... other code here ...
    string GetTile(int x, int y)
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            return sLevel[y * nLevelWidth + x];
        else
            return "";
    }

No lambdas required.

Note that this solution requires C# 7.0 or higher.

(An even better solution would be to put all this code into a class; make a custom data type that does this work for you. But you asked specifically about how to port this code directly, not how to refactor it.)

2
  • Can you kindly please explain why the function that you wrote in your answer needs C# 7.0 or higher? What is it that it's doing that is not supported with anything lower than 7.0? Thank you and it's a pleasure to follow your daily answers!
    – Zuzlx
    Feb 14, 2020 at 19:27
  • 3
    @Zuzlx: Support for local functions was added in C# 7; lambdas were added (by me!) in C# 3, and anonymous delegates were added in C# 2; in C# 1 there was no way at all to make a function inside another. So if you are using C# 3, 4, 5 or 6, you should use a lambda to make a local function. Feb 14, 2020 at 20:03
0

Lambda Expressions doesn't have a compile time type, but is convertible to any matching delegate or expression type. That's why according to MSDN lambda expressions can't be implicitly typed (also check this answer by Eric Lippert

So:

Func<int, int, string> GetTile = (int x, int y) =>
{
    if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
        return sLevel[y * nLevelWidth + x];
    else
        return "";
};

Action<int, int, string> SetTile = (int x, int y, string c)=>                
{
   if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
       sLevel[y * nLevelWidth + x] = c;
};
0

You can declare two delegates like below:

delegate void ActionRef(ref int x, ref int y, string c);
delegate string FuncRef(ref int x, ref int y);

And instead of using var, you can these delegates as the type of function.

public GameLogic()
{
    FuncRef GetTile = (ref int x, ref int y) =>
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            return sLevel[y * nLevelWidth + x];
        else
            return "";
    };

    ActionRef SetTile = (ref int x, ref int y, string c) =>
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            sLevel[y * nLevelWidth + x] = c;
    };
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.