Wildhorn
Wildhorn

Reputation: 932

C# GetType().GetField at an array position

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

Answers (6)

Wildhorn
Wildhorn

Reputation: 932

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

Upvotes: 0

Richard Friend
Richard Friend

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

LukeH
LukeH

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

Achim
Achim

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

Iain Ward
Iain Ward

Reputation: 9936

Why not just do this

tName[0] = "TheNewValue";

Upvotes: 0

sbenderli
sbenderli

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

Related Questions