step through a struct using foreach

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

    step through a struct using foreach

    Can I step through a struct using foreach? I want a method that steps
    through a struct, and prints out the name/value of each member. Can
    it be done?

    The error I get when trying this is: "foreach statement cannot
    operate on variables of type '...' because '...' does not contain a
    public definition for 'GetEnumerator' . And it points me to


    I guess this is the answer, but it is over my head at this moment.

  • Marc Gravell

    #2
    Re: step through a struct using foreach

    What do you mean, "steps through a struct"? If you mean the
    sub-properties, then something like

    foreach(Propert yDescriptor property in
    TypeDescriptor. GetProperties(m yValue)) {
    Debug.WriteLine (property.GetVa lue(myValue),
    property.Name);
    }

    may suffice...

    Marc


    Comment

    • titan nyquist

      #3
      Re: step through a struct using foreach

      Marc,

      Here's example code (that does not work) of what I was trying to do:

      namespace DisplayStructCo ntentsTest
      {
      class Program
      {

      struct Employee
      {
      public string name;
      public int age;
      public string location;
      };

      static void Main(string[] args)
      {
      Employee employee;

      employee.name = "Jim Smith";
      employee.age = 35;
      employee.locati on = "California ";

      foreach (object obj in employee)
      {
      Console.WriteLi ne(obj + " = " + obj.ToString()) ;

      // Output I wish for:
      //
      // name = Jim Smith
      // age = 35
      // location = California
      }


      }
      }
      }

      Comment

      • titan nyquist

        #4
        Re: step through a struct using foreach

        The point is, if I modify the struct, I want the code to automatically
        handle the new structure. For example, if I add a "birthdate" field,
        the code should (without modification) display the birthdate.

        Comment

        • Marc Gravell

          #5
          Re: step through a struct using foreach

          Exposing fields forces you to use reflection; very similar to the
          component model code:

          foreach (FieldInfo fi in employee.GetTyp e().GetFields() ) {
          Console.WriteLi ne(fi.Name + " = " +
          Convert.ToStrin g(fi.GetValue(e mployee)));
          }

          But!! I can't tell you how to code, but you are a: using public
          fields, and b: using mutable structs. Neither of these is particularly
          good practice in .Net. Please note that CLR structs are very different
          to C[++] structs; they are not the same, and perhaps it was
          unfortunate to call them structs in C#. What you have feels more like
          a class. The public fields are marginally less critical, but prevent
          you from doing any find of validation / notification, or changing the
          model. I strongly advise using .Net the way it is intended, i.e.
          (short version):

          class Employee {
          private string name, location;
          private int age;
          public string Name { get { return name; } set { name =
          value; } }
          public string Location { get { return location; } set {
          location = value; } }
          public int Age { get { return age; } set { age =
          value; } }
          };

          This obeys a lot more CLR conventions, and will work more as expected
          in collections etc.

          Marc


          Comment

          • Marc Gravell

            #6
            Re: step through a struct using foreach

            Don't worry... we get it ;-p See other post.

            However; this precisely illustrates my point re properties. When you
            add the "birthdate" , you might want to cease having "age" as a field,
            and start using a calculated "get", i.e. using the offset from
            DateTime.Now when the "get" is called.

            Marc


            Comment

            • Tom Porterfield

              #7
              Re: step through a struct using foreach

              titan nyquist wrote:
              The point is, if I modify the struct, I want the code to automatically
              handle the new structure. For example, if I add a "birthdate" field,
              the code should (without modification) display the birthdate.
              The following should do it:

              Employee employee;

              employee.name = "Jim Smith";
              employee.age = 35;
              employee.locati on = "California ";

              Type t = employee.GetTyp e();
              System.Reflecti on.FieldInfo [] fields =
              t.GetFields(Sys tem.Reflection. BindingFlags.In stance|System.R eflection.Bindi ngFlags.Public) ;

              foreach (System.Reflect ion.FieldInfo field in fields)
              {
              Console.WriteLi ne(field.Name + " = " + field.GetValue( employee));
              }
              --
              Tom Porterfield

              Comment

              Working...