Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I learn the ins and outs of enumerators in C#? [closed]

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.

like image 540
NibblyPig Avatar asked Mar 25 '10 11:03

NibblyPig


People also ask

What is enumeration in C++?

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++.

What is the use of enum in 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.

What are the requirements for ENUM names?

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.

What is an example of enumeration in Python?

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.


2 Answers

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.

like image 190
leppie Avatar answered Nov 10 '22 08:11

leppie


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.

like image 23
Priscilla Tse Avatar answered Nov 10 '22 06:11

Priscilla Tse