0

Here I just got a scene like : here what i am doing is i am declaring 5 string variables and assiging null , two arrays out of which 1st array has got the list of string variable name and 2nd array containing the values which needs to be assigned to the 5 string variables declared as below :

 string slot1=null,slot2=null,slot3=null,slot4=null,slot5=null;
    string[] a=new string[5]{slot1,slot2,slot3,slot4,slot5};
    string[] b=new string[5]{abc,def,ghi,jkl,mno};
    for(int i=0;i<a.length;i++)
    {
    //here i want to do is dynamically find the variable (for ex. slot1) or you can say a[i] and assign the value from b[i] (for ex. abc) to it.
    }

how to implement this ?????

  • If you assign a new string to `a[0]` it doesn't change `slot1`. They become two different references at that point. Why do you need `slot1`, `slot2`, etc, are separate variables? – Enigmativity Dec 12 '15 at 06:51
  • What you are looking for is something like [this](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – mojorisinify Dec 12 '15 at 06:59

2 Answers2

1
string slot1 = null, slot2 = null, slot3 = null, slot4 = null, slot5 = null;
string[] a = new string[5]{slot1,slot2,slot3,slot4,slot5};
string[] b = new string[5]{abc,def,ghi,jkl,mno};

for(int i=0; i<a.length; i++)
{
    FieldInfo prop = this.GetType().GetField(a[i]);
    if(prop!=null) prop.SetValue(this, b[i]);
}  

Hope this helps.... Thank You

khaled4vokalz
  • 876
  • 9
  • 13
0

You are looking for something like this: References : 1

public static void Main()
{

string[] a= new string[5]{"Slot1","Slot2","Slot3","Slot4","Slot5"};
string[] b= new string[5]{"abc","def","ghi","jkl","mno"};

var whatever = new Whatever();
for(int i = 0; i < a.Length;  i++)
    {
        var prop = a[i];
        var value = b[i];
        Console.WriteLine(prop);
        var propertyInfo = whatever.GetType().GetProperty(prop);
        Console.WriteLine(propertyInfo);
        if(propertyInfo != null) propertyInfo.SetValue(whatever, value,null);

    }

    Console.WriteLine(whatever.ToString());


}

public class Whatever {
public string Slot1{get;set;}
public string Slot2{get;set;}
public string Slot3{get;set;}
public string Slot4{get;set;}
public string Slot5{get;set;}

public override string ToString(){

return "Slot 1 : " + Slot1  + "\n" +
"Slot 2 : " + Slot2  + "\n" +
"Slot 3 : " + Slot3  + "\n" +
"Slot 4 : " + Slot4  + "\n" +
"Slot 5 : " + Slot5 ;
}
}
Community
  • 1
  • 1
mojorisinify
  • 377
  • 5
  • 22