The yield keyword is used in an iterator block to provide a value
to the enumerator object or to signal the end of the iteration. When
used the expression is evaluated and returned as a value to the
enumerator object. Note the expression has to be implicitebly
convertible to yield type of the iterator.
public static IEnumerable GetIntCollectionFromString(string SomeString)
{
string[] val = SomeString.Split(‘ ‘);
int intToAdd;
foreach (string token in val)
{
if (int.TryParse(token, out intVal))
{
yield return intVal;
}
else
{
yield break;
}
}
}
Here since we are using the yield keyword the function will return the collection of intVal instead of the value of intVal. The statement will only return when the iteration of the loop is complete.
public static IEnumerable
{
string[] val = SomeString.Split(‘ ‘);
int intToAdd;
foreach (string token in val)
{
if (int.TryParse(token, out intVal))
{
yield return intVal;
}
else
{
yield break;
}
}
}
Here since we are using the yield keyword the function will return the collection of intVal instead of the value of intVal. The statement will only return when the iteration of the loop is complete.
No comments:
Post a Comment