I want to be able to set some variables in C# by reading a text config file. I created a function "ReadConfigFile()" that reads the file and returns an array of strings.
Example output of ReadConfigFile():
[Variable1=1234, Variable2=true, Variable3=MyCatIsGray]
Currently the way I'm setting my variables using the array is by using a bunch of if statements like the code bellow shows. But obviously this becomes quite tedious if I'm using proper names for my variables, and I if I want to have a lot more variables.
public int Variable1 = 0;
public bool Variable2 = false;
public string Variable3 = "";
public void Configure()
{
string[] config = ReadConfigFile();
foreach (string line in config)
{
string[] variableAndValueArray = line.Split("=");
if (variableAndValueArray[0] == "Variable1") { Variable1 = VariableAndValueArray[1]; }
if (variableAndValueArray[0] == "Variable2") { Variable2 = VariableAndValueArray[1]; }
if (variableAndValueArray[0] == "Variable3") { Variable3 = VariableAndValueArray[1]; }
}
}
So I was wondering if there was a better way of doing this. I was hoping something like this would be possible:
public int Variable1 = 0;
public bool Variable2 = false;
public string Variable3 = "";
public void Configure()
{
string[] config = ReadConfigFile();
foreach (string line in config)
{
string[] variableAndValueArray = line.Split("=");
variableAndValueArray[0] = variableAndValueArray[1]
//I want the line above to change which variable it is setting based
//on the value of variableAndValueArray[0]
}
}
I've tried to look up information about doing something like this but since I don't know the proper terminology for things, it was hard finding anything.
@WhyV - You'll have to use reflection. Check out the following code
internal class Program
{
static void Main(string[] args)
{
SO temp = new SO();
temp.Configure();
}
}
class SO
{
public int Variable1 = 0;
public bool Variable2 = false;
public string Variable3 = "";
public void Configure()
{
string[] config = new string[] { "Variable1 = 1234", "Variable2 = true", "Variable3 = MyCatIsGray" };
foreach (string line in config)
{
var variableNamePart = line.Split('=')[0];
var variableValuePart = line.Split('=')[1];
variableNamePart = variableNamePart.Trim();
variableValuePart = variableValuePart.Trim();
FieldInfo fld = typeof(SO).GetField(variableNamePart);
if (fld.FieldType == typeof(System.Int32))
{
fld.SetValue(this, int.Parse(variableValuePart));
}
if (fld.FieldType == typeof(System.Boolean))
{
fld.SetValue(this, Boolean.Parse(variableValuePart));
}
if (fld.FieldType == typeof(System.String))
{
fld.SetValue(this, variableValuePart);
}
}
Console.WriteLine("Variable1 is " + Variable1);
Console.WriteLine("Variable2 is " + Variable2);
Console.WriteLine("Variable3 is " + Variable3);
}
}