Is there a good resource out there that explains the concept of enumerators and custom enumerators? Particularly one with a good solid example of why you would want to implement IEnumerable
yourself and how you would use it effectively?
I occasionally come across yield
and I am trying to get a better understanding of it.
Last Updated : 21 Dec, 2018. Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. enum State {Working = 1, Failed = 0}; The keyword ‘enum’ is used to declare new enumeration types in C and C++.
It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an example of enum declaration. // The name of enumeration is "flag" and the constant // are the values of the flag.
The value assigned to enum names must be some integeral constant, i.e., the value must be in range from minimum possible integer value to maximum possible integer value. 5. All enum constants must be unique in their scope. For example, the following program fails in compilation.
They can be defined in two ways: In the above example, we declared “day” as the variable and the value of “Wed” is allocated to day, which is 2. So as a result, 2 is printed. Another example of enumeration is: In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is Jan which is 0 and the value of Dec is 11.
The easiest example:
IEnumerable<string> GetNames()
{
yield return "Bob";
yield return "Bob's uncle";
yield return "Alice";
yield return "Stacy";
yield return "Stacy's mom";
}
Usage:
foreach (var name in GetNames())
{
Console.WriteLine(name);
}
To see it in action, place a debugger breakpoint on every line in the GetNames
method.
Another book I found quite useful when I was learning about IEnumerable and IEnumerator is Troelsen's Pro C# 2008 book. It explains what the interfaces contain and how to build iterators with the "yield" keyword.
Hope this help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With