TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# GetEnumerator: While MoveNext, Get Current

Use the GetEnumerator method on the List type. Call MoveNext and access Current.
GetEnumerator. Some collection types offer the GetEnumerator method. This method returns an Enumerator object that can be used to loop through the collection. Complete knowledge of the actual collection type is not needed.
Example. This program shows how the GetEnumerator method on the List type works. On a List(int), GetEnumerator returns a List(int) Enumerator object. This object implements IEnumerator(int). We can then write methods that receive IEnumerator(int).List

IEnumerator: With GetEnumerator, it becomes possible to write methods that act on the IEnumerator interface.

Info: IEnumerator is not the same as IEnumerable. It is an interface implemented by Enumerator objects.

Loops: IEnumerable is a collection that can be looped over with foreach-loops. This is how it is usually used.

Foreach
C# program that uses GetEnumerator using System; using System.Collections.Generic; class Program { static void Main() { List<int> list = new List<int>(); list.Add(1); list.Add(5); list.Add(9); List<int>.Enumerator e = list.GetEnumerator(); Write(e); } static void Write(IEnumerator<int> e) { while (e.MoveNext()) { int value = e.Current; Console.WriteLine(value); } } } Output 1 5 9
Other collection types also provide GetEnumerator. For example, LinkedList returns LinkedList(int) Enumerator. This object too can be passed to the Write method in the example above.LinkedListDictionary: GetEnumerator

Thus: We only have to have one Write method to handle all generic enumerators that handle integers.

Summary. GetEnumerator is an instance method provided on several different collection types. It can help in the development of abstractions in programs. A unified method can be used to loop over the Enumerator returned by all these collections.Interface
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf