0

I have a test class that I created and I want to be able to create multiple instances of it. Then I want to use foreach to iterate thru each instance. I have seen several forums that show IEnumerate but being a very newbe they have me confused. Can anyone please give me a newbe example.

My class:

using System;
using System.Collections;
using System.Linq;
using System.Text

namespace Test3
{
  class Class1
  {
    public string   Name    { get; set; }
    public string   Address { get; set; }
    public string   City    { get; set; }
    public string   State   { get; set; }
    public string   Zip     { get; set; }  
  }
} 

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

2

Do you need to enumerate through multiple instances of your type, or create a type that is itself enumerable?

The former is easy: add instances to a collection, such as List<T>() which implement IEnumerable<T>.

// instantiate a few instances of Class1
var c1 = new Class1 { Name = "Foo", Address = "Bar" };
var c2 = new Class1 { Name = "Baz", Address = "Boz" };

// instantiate a collection
var list = new System.Collections.Generic.List<Class1>();

// add the instances
list.Add( c1 );
list.Add( c2 );

// use foreach to access each item in the collection
foreach( var item in list ){
   System.Diagnostics.Debug.WriteLine( item.Name );
}

When you use a foreach statement, the compiler helps out and automatically generates the code needed to interface with the IEnumerable (such as a list). In other words, you don't need to explicitly write any additional code to iterate through the items.

The latter is a bit more complex, and requires implementing IEnumerable<T> yourself. Based on the sample data and the question, I don't think this is what you are seeking.

Community
  • 1
  • 1
Tim M.
  • 53,671
  • 14
  • 120
  • 163
1

Your class is just a "chunk of data" - you need to store multiple instances of your class into some kind of collection class, and use foreach on the collection.

John3136
  • 28,809
  • 4
  • 51
  • 69
0
// Create multiple instances in an array

Class1[] instances = new Class1[100];
for(int i=0;i<instances.Length;i++) instances[i] = new Class1();

// Use foreach to iterate through each instance
foreach(Class1 instance in instances) {

    DoSomething( instance );
}
Dai
  • 141,631
  • 28
  • 261
  • 374