c# list and enumerator with properties -


i have following problem: have list , add string items list. create enumerator out of list. when loop through list movenext() command works when access enumerator directly. when use enumerator properties access enumerator doesn't work. movenext() command doesn't increment index.

here code used. lot help.

public class dummyklasse {     public list<string>.enumerator enumerator;     public list<string> list;      public dummyklasse()     {         console.writeline("test");         list = new list<string>();         enumerator = new list<string>.enumerator();     }      public list<string>.enumerator enumerator     {         { return enumerator; }         set { enumerator = value;}     }      public list<string> list     {         { return list; }         set { list = new list<string>(value); }     }              public void dummyfunction()     {         list.add("test1");         list.add("test2");          enumerator = list.getenumerator();     } }  public class program {     static void main(string[] args)     {         dummyklasse dummyklasse = new dummyklasse();         dummyklasse.dummyfunction();          //does not work properties         /*         while (dummyklasse.enumerator.movenext())         {             console.writeline(dummyklasse.enumerator.current);         }         */         //works without properties         while (dummyklasse.enumerator.movenext())         {             console.writeline(dummyklasse.enumerator.current);         }          console.readline();     } } 

list<t>.enumerator struct, in while loop, each time access enumerator property, calling getter, return new copy of enumerator each time. enumerator point item before th beginning of list, , each call movenext , current done on different copy of enumerator.

as result on non-empty list, movenext return true, , enumerator.current null.

if access field directly, avoiding copy , same enumerator being accessed calls movenext , current.

if change code to:

using (var enumerator = dummyklasse.enumerator) {     while (enumerator.movenext())     {         console.writeline(enumerator.current);     } } 

it work expected. note similar foreach statement does.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -