Problem while porting VB.NET Code to C#
Question
Currently I am trying to port some VB.NET code to C#.
The struct looks like this in VB.NET:
Public Structure sPos
Dim x, y, z As Single
Function getSectorY() As Single
Return Math.Floor(y / 192 + 92)
End Function
Function getSectorX() As Single
Return Math.Floor(x / 192 + 135)
End Function
Function getSectorXOffset() As Int32
Return ((x / 192) - getSectorX() + 135) * 192 * 10
End Function
Function getSectorYOffset() As Int32
Return ((y / 192) - getSectorY() + 92) * 192 * 10
End Function
End Structure
C# Version of the struct:
public struct sPos
{
public float x;
public float y;
public float z;
public float getSectorY()
{
return (float)Math.Floor(y / 192 + 92);
}
public float getSectorX()
{
return (float)Math.Floor(x / 192 + 135);
}
public Int32 getSectorXOffset()
{
return (int)((x / 192) - getSectorX() + 135) * 192 * 10;
}
public Int32 getSectorYOffset()
{
return (int)((y / 192) - getSectorY() + 92) * 192 * 10;
}
}
Why do I have to cast the return values to float & int ? In the vb version I don't have to..
Thanks everyone.
Solution
Put a ()
after getXSectorOffset
because it's a function?
example:
nullPointX = pictureBox1.Width / 2 - sectorsize - centerPos.getSectorXOffset() / 10 * sectorsize / 192;
Regarding the second question, you could avoid cast to float with this modification:
public float getSectorY()
{
return (float)Math.Floor(y / 192f + 92f);
}
And sorry, you'll have to cast to int
still. Unless you cast the x
and getXOffset()
to int
during the function:
public Int32 getSectorXOffset()
{
return (((int)x / 192) - (int)getSectorX() + 135) * 192 * 10;
}
OTHER TIPS
Note that you shouldn't use "Dim" on class/structure level variables. Always use Public, Protected, Private etc.
Also note that division works differently in VB and C#. In VB, if you divide two integers like so:
Dim r As Double = 5/2
Then r will be a Double with value 2.5
In C# however, division with integers gives you integer results, 2 in this case.
If you set Option Strict On in your VB code (which you really ought to always do) then I think you'd need to cast the return values in VB as well: Math.Floor() returns a Double, not a Single, and you should really tell the compiler that you wanted to lose that precision (which is what the (float) cast in the C# version does) rather than letting the compiler throw precision away without you making an informed decision.