Evaluating Dynamic Property Names

  • Thread starter Thread starter M
  • Start date Start date
M

M

I am accessing properties in an object that has the field names
"a1desc", "a2desc", "a3desc", etc. I want to be able to access each of
them in a loop. Is it possible?

I know the following doesn't work, I'm just using it as an
illustration.

string value="";
for(int i=0;i<orderInfo.Length;i++){
value = orderInfo.a + i + desc;
}//for
 
Hi M,

The magic word is reflection.
Check out the example below:
class Class1

{

private int i = 5;

public int j = 8;

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main(string[] args)

{

Class1 c = new Class1();

FieldInfo[] fis = typeof(Class1).GetFields(BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic);

foreach (FieldInfo fi in fis)

Console.WriteLine(fi.Name + " = " + fi.GetValue(c));

Console.ReadLine();

}

}

If you want set the field value call SetValue instead of GetValue.

If you want to get/set properties, use PropertyInfo[] pis = ...GetProperties

HTH
 
Back
Top