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 ?????

2
  • 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? Commented Dec 12, 2015 at 6:51
  • What you are looking for is something like this Commented Dec 12, 2015 at 6:59

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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 ;
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.