-1

I have 3 variables called gxpos, gypos and gzpos. I have a method called moove(), with a string argument axis (x, y or z) which I want to be able to change the value of both 3 variables (gxpos, gypos, gzpos).

In the code sample, I have represented the locations where I want to have the axis variable by this ?.

public void moove(string axis)
{ 
    g(?)pos = (?)pos + trkSizeStep.Value;
    if (g(?)pos != m(?)pos || -g(?)pos != m(?)pos)
    {
        (?)pos = g(?)pos;
        port.WriteLine(axis + (?)pos);
        lblpos(?).Text = (?)pos.ToString();
    }
    else
    {
        errorLimit(axis, 1);
    }
}
Zain Arshad
  • 1,885
  • 1
  • 11
  • 26

2 Answers2

0

This is not possible in C# without reflection or the use of external tools such as T4 Templates.

However, you may be able to get around this by using arrays:

int[] gpos = new int[] { gxpos, gypos, gzpos };
int[] pos = new int[] { xpos, ypos, zpos };
int[] mpos = new int[] { mxpos, mypos, mzpos };
string axisNames = new string[] { "x", "y", "z" };

public void moove(int axis)
{
    gpos[axis] = pos[axis] + trkSizeStep.Value;
    if (gpos[axis] != mpos[axis] || -gpos[axis] != mpos[axis])
    {
        pos[axis] = gpos[axis];
        port.WriteLine(axisNames[axis] + pos[axis]);
        lblpos[axis].Text = pos[axis].ToString();
    }
    else
    {
        errorLimit(axisNames[axis], 1);
    }
}

Or better yet, take advantage of Vector<T> and friends

PC Luddite
  • 5,883
  • 6
  • 23
  • 39
0

Using Dictionaries:

var gpos = new Dictionary<string, int> { { "x", 0 }, { "y", 0 }, { "z", 0 } };
var mpos = new Dictionary<string, int> { { "x", 0 }, { "y", 0 }, { "z", 0 } };
var pos = new Dictionary<string, int> { { "x", 0 }, { "y", 0 }, { "z", 0 } };
var lblpos = new Dictionary<string, Label> { { "x", lblxpos }, { "y", lblypos }, { "z", lblzpos } };

public void moove(string axis)
{
    gpos[axis] = pos[axis] + trkSizeStep.Value;
    if (gpos[axis] != mpos[axis] || -gpos[axis] != mpos[axis])
    {
        pos[axis] = gpos[axis];

        port.WriteLine(axis + pos[axis]);

        lblpos[axis].Text = pos[axis].ToString();

    }
    else
    {
        errorLimit(axis, 1);
    }
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104