Quote:
Originally Posted by amigo1
Code:
void Main()
{
myClass mc = new myClass();
foreach (char ch in mc)
Console.WriteLine(ch);
}
class myClass
{ char[] chrs = new char[] {'A','B','C','D','E','F'} ;
//this iterator returns the characters in the char array
public IEnumerator GetEnumerator()
{ foreach (char c in chrs)
yield return c; // omitting this statement will Not return a value:- 'UserQuery.myClass.GetEnumerator() ': not all code
// paths return a value
//actually this statement creates the iterator block
Console.WriteLine(chrs);
// why does c in WriteLine : 'c' does not exist in the current context. puttting chrs in WriteLine makes the query successful
}
}
|
The variable 'c' is declared within the foreach statement, and only valid within the foreach statement block. As you do not declare a block, you have only a single statement in the foreach: yield return. After this statement, the variable 'c' is not declared and thus not available in the context.
If you add curly brackets to the foreach, you can use the 'c' variable.