IEnumerable<KeyValuePair<string, string>> implementation |
| Rune Funch Søltoft replied to Chris Falter at 25-Apr-08 04:02 |
The implementation with yield return could look like this
public static IEnumerable<KeyValuePair<string, string>> KeyValuePairs { get { MaritalStatus ms = new MaritalStatus(MaritalStatus.Married); foreach (KeyValuePair<string, string> kvp in ms.LookupDict) yield return kvp; } } There's two main differences to the above implementation. It's documented more clearly that it's "readonly" there's no way to change the elements in the IEnumerable (unless u really try hard, figuring out the actual implementation, casting/using reflection and then ur on ur own :-) ) the second difference is that the implementation here use lazy evaluation.
writing code like: var pairs = MaritalStatus.KeyValuePairs; will not actually execute the foreach loop. if u later write something like
var enumerator = pairs.GetEnumerator(); var firstKey = enumerator.MoveNext() ? enumerator.Current.Key : "not found"; u still havent iterated the entire LookupDict but only the first element
hope this clearify my point from the above post
|
|