If you have variables p1
, p2
and you want to reference them by using number, then:
Solution 1, create helper method
string PX(int number)
{
switch(number)
{
case 1: return p1;
case 2: return p2;
}
// or
if(number == 1) return p1;
if(number == 2) return p2;
}
// usage
PX(x).Contains(blablabla);
Solution 2, use indexes
// helper array
string[] px = new string[] {p1, p2};
// usage
px[i - 1].Contains(blablabla);
or
// helper array
string[] px = new string[] {null, p1, p2};
// usage
px[i].Contains(blablabla);
Solution 3, use key-value collections.
Solution 4, use reflection.
Solutions 3 and 4 are slower and with unnecessary overhead. Indexes are fast, having helper method or helper array is not too much, consider following when constructing properties
private string[] _px = string[2];
public string[] PX { get { return px; } }
public string P1
{
get { return _px[0]; }
set { _px[0] = value; }
}
public string P2
{
get { return _px[1]; }
set { _px[1] = value; }
}
This way data are initially saved in array = you don't waste memory, while having possibility to access values by index PX[index]
or by name P1
/P2
.