foreach - IEnumerable vs Property

  • Thread starter Thread starter J. Marcelo Barbieri
  • Start date Start date
J

J. Marcelo Barbieri

I managed to do a foreach to go through all the elements in class2 using a
public property, as you can find bellow.

I know I could obtain the same result implementing the IEnumerable
interface, but what would be the difference???

thanks,



namespace IndexerTest

{

class Class1

{



static void Main(string[] args)

{

int len = 2;

Class2 c2 = new Class2(len);

c2[0] = "First String";

c2[1] = "Second String";

foreach(string s in c2)...



}

}

public class Class2

{

public Class2(){}

public Class2(int i)

{

sa = new string;

}

private string[] sa;

public string this[int i]

{

get{return sa;}

set{sa = value;}

}

public string[]saProperty

{ get{return string[]sa;} }

}

}
 
You use GetEnumerator (IEnumerator). Let's say:

(found in MSDN)

using System;

public class SamplesArray {

public static void Main() {

// Creates and initializes a new Array.
String[] myArr = new String[10];
myArr[0] = "The";
myArr[1] = "quick";
myArr[2] = "brown";
myArr[3] = "fox";
myArr[4] = "jumped";
myArr[5] = "over";
myArr[6] = "the";
myArr[7] = "lazy";
myArr[8] = "dog";

// Displays the values of the Array.
int i = 0;
System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
Console.WriteLine( "The Array contains the following values:" );
while (( myEnumerator.MoveNext() ) && ( myEnumerator.Current !=
null ))
Console.WriteLine( "[{0}] {1}", i++, myEnumerator.Current );

}

}
 
IEnumerable gives you the ability to determine how a collection is sorted.
IEnumerable implements the IEnumerator interface. This interface has the
public methods MoveNext and Reset. How you implement these functions is up
to you.
 
J. Marcelo Barbieri,

Use something like:

public class Class2 : System.Collections.IEnumerable
{
// extra stuff trimmed

private string[] sa;

// extra stuff trimmed

#region IEnumerable support

public System.Collections.IEnumerator GetEnumerator()
{
return sa.GetEnumerator();
}

#endregion

}

Then you can delete the public saProperty property.

Hope this helps
Jay
 
Back
Top