views:

61

answers:

6
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.

+3  A: 

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>));
sbenderli
A: 

Why not just do this

tName[0] = "TheNewValue";
w69rdy
/sigh I made my example simple to make it clear.
Wildhorn
A: 

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";
Richard Friend
You don't need to set the array back - modifying it in place is enough
Tim Robinson
Do you think the last line is really required?
Achim
+4  A: 

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! ;-)

Achim
+1  A: 
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;
}
LukeH
A: 

I gave up and splitted the table in 3 different variables.

Wildhorn