Search code examples
c#vb.netcode-translation

Conversion of VB code to C#


I'm new at C# and i would like to make my former VB program run in C# too. I got a little problem with VB's byRef, i can't translate it to C#.

So here's my code in VB:

Sub LepesEllenorzes(ByRef Gomb1 As Button, ByRef Gomb2 As Button)
    If Gomb2.Text = " " Then 'if a button is empty
        Gomb2.Text = Gomb1.Text 'change the numbers on them
        Gomb1.Text = " "
    End If
End Sub

And here's my code in C#, but doesn't working properly:

public Lépés(ref Button but1, ref Button but2)
{
       if (but2.Text == "")
       {
                but2.Text = but1.Text;
                but1.Text = "";
       }                
}

The code is from a number shuffle game, what checks, if one of the two neighbour button is empty, so the button with a number on it will change place with the empty button.

Sorry for my English, I hope you'll understand my problem.


Solution

  • Unless this is a constructor (which I highly doubt) then you need a return type. If there's nothing being returned, void works:

    public void Lépés(ref Button but1, ref Button but2)
    {
            if (but2.Text == "")
            {
                but2.Text = but1.Text;
                but1.Text = "";
            }                
    }
    

    Second, you don't need ref here:

    public void Lépés(Button but1, Button but2)
    {
            if (but2.Text == "")
            {
                but2.Text = but1.Text;
                but1.Text = "";
            }                
    }
    

    These are reference types by default, and unless you have very specific reasons to use them you shouldn't default to ref parameters.