How to access struct elements sequentially?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rick

    #1

    How to access struct elements sequentially?

    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
  • Bret Mulvey

    #2
    Re: How to access struct elements sequentially?

    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.Reflecti on.FieldInfo[] fields = type.GetFields( );
    foreach (System.Reflect ion.FieldInfo fieldInfo in fields)
    {
    object fieldValue = fieldInfo.GetVa lue(p);
    System.Diagnost ics.Trace.Write Line(fieldValue );
    }
    }
    }


    "Rick" <rbrown@allstat e.com> wrote in message
    news:500a18df.0 309260737.b59e0 6f@posting.goog le.com...[color=blue]
    > 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[/color]


    Comment

    Working...