Reputation: 932
public string[] tName = new string[]{"Whatever","Doesntmatter"};
string vBob = "Something";
string[] tVars = new string[]{"tName[0]","vBob","tName[1]"};
Now, I want to change the value of tName[0], but it doesnt work with:
for(int i = 0; i < tVars.Lenght;++i)
{
this.GetType().GetField("tVars[0]").SetValue(this, ValuesThatComeFromSomewhereElse[i]));
}
How can I do this?
EDIT: Changed code to show more exactly what I am trying to do.
Upvotes: 3
Views: 4415
Reputation: 16018
You can get the existing array, modify it and set it back to the field like so..
string [] vals = (string [])this.GetType().GetField("tName").GetValue(this);
vals[0] = "New Value";
Upvotes: 0
Reputation: 269438
SetUsingReflection("tName", 0, "TheNewValue");
// ...
// if the type isn't known until run-time...
private void SetUsingReflection(string fieldName, int index, object newValue)
{
FieldInfo fieldInfo = this.GetType().GetField(fieldName);
object fieldValue = fieldInfo.GetValue(this);
((Array)fieldValue).SetValue(newValue, index);
}
// if the type is already known at compile-time...
private void SetUsingReflection<T>(string fieldName, int index, T newValue)
{
FieldInfo fieldInfo = this.GetType().GetField(fieldName);
object fieldValue = fieldInfo.GetValue(this);
((T[])fieldValue)[index] = newValue;
}
Upvotes: 1
Reputation: 15712
Don't know if it's a good idea to do what you try to do, but this should work:
((string[])GetType().GetField("tName").GetValue(this))[0] = "TheNewValue";
I think it would be good idea to split it in multiple statements! ;-)
Upvotes: 5
Reputation: 3794
The field's name isn't 'tName[0]', it is 'tName'. You would need to set the value to another array, whose 0 index is the value you want.
this.GetType().GetField("tName").SetValue(this, <Your New Array>));
Upvotes: 3