How to access struct elements sequentially?

  • Thread starter Thread starter Rick
  • Start date Start date
R

Rick

I would like to be able to access the members of a struct (or class)
based on their order within the struct. For example, say I had a
struct something like:

public struct PhoneTypes
{
public string work;
public string home;
public string mobile;
}

Is there some way I can directly access the first element (work), then
the next (home), etc, without using the specific element names?

Thanks!

~ Rick
 
Here's an example.

public struct PhoneTypes
{
public string work;
public string home;
public string mobile;
}

class Class1
{
[STAThread]
static void Main(string[] args)
{
PhoneTypes p;
p.work = "425-555-1212";
p.home = "206-555-1212";
p.mobile = String.Empty;

Type type = p.GetType();
System.Reflection.FieldInfo[] fields = type.GetFields();
foreach (System.Reflection.FieldInfo fieldInfo in fields)
{
object fieldValue = fieldInfo.GetValue(p);
System.Diagnostics.Trace.WriteLine(fieldValue);
}
}
}
 
Back
Top