SlideShare a Scribd company logo
1 of 6
Download to read offline
13
Collection Objects
Earlier we used an array in a foreach. If the array had three members, the foreach got executed
three times and each time the variable i had a different value. The concept described below is
called a collection class. It is a class that returns a value each time till the values run out, thus
making it easier for us to iterate through the array.

        a.cs
        public class zzz
        {
        public static void Main()
        {
        yyy f = new yyy();
        foreach (string i in f)
        {
        }
        }
        }
        class yyy
        {
        }


        Compiler Error
        a.cs(6,1): error CS1579: foreach statement cannot operate on variables of type ‘yyy’
        because ‘yyy’ does not contain a definition for ‘GetEnumerator’, or it is inaccessible

To use yyy in a foreach as a collection class, foreach requires a function GetEnumerator.

        a.cs
        public class zzz
        {
        public static void Main()
        {
        yyy f = new yyy();
        foreach (string i in f)
        {
        }
        }
        }
        class yyy
{
       public int GetEnumerator()
       {
       }
       }

       Compiler Error
       a.cs(6,1): error CS1579: foreach statement cannot operate on variables of type 'yyy'
       because 'int' does not contain a definition for 'MoveNext', or it is inaccessible
       a.cs(13,12): error CS0161: 'yyy.GetEnumerator()': not all code paths return a value

Foreach obviously tries to execute the function called GetEnumerator. This function should not
return an int but something else as the error suggests.




       a.cs
       using System.Collections;
       public class zzz
       {
       public static void Main()
       {
       yyy f = new yyy();
       foreach (string i in f)
       {
       }
       }
       }
       class yyy
       {
       public IEnumerator GetEnumerator()
       {
       return new xxx();
       }
       }
       class xxx : IEnumerator
       {
       }

       Compiler Error
       a.cs(19,7): error CS0535: ‘xxx’ does not implement interface member
       ‘System.Collections.IEnumerator.MoveNext()’
       a.cs(19,7): error CS0535: ‘xxx’ does not implement interface member
       ‘System.Collections.IEnumerator.Reset()’
       a.cs(19,7): error CS0535: ‘xxx’ does not implement interface member
       ‘System.Collections.IEnumerator.Current’

IEnumerator is an interface which has three functions MoveNext, Reset and Current and xxx has
to implement all of them to remove the compiler errors.

       a.cs
       using System.Collections;
public class zzz
        {
        public static void Main()
        {
        yyy f = new yyy();
        foreach (string i in f)
        {
        System.Console.WriteLine(i);
        }
        }
        }
        class yyy
        {
        public IEnumerator GetEnumerator()
        {
        return new xxx();
        }
        }
        class xxx : IEnumerator
        {
        public bool MoveNext()
        {
        System.Console.WriteLine(“MoveNext”);
        return true;
        }
        public void Reset()
        {
        System.Console.WriteLine(“Reset”);
        }
        public object Current
        {
        get
        {
        System.Console.WriteLine(“Current”);
        return “hi”;
        }
        }
        }

Run the program and you will notice that the output does not stop. It goes on forever.
IEnumerator is an interface which belongs to the namespace System.Collections. foreach first
calls the function GetEnumerator from yyy. It expects this function to return an object like
IEnumerator. It then calls the function MoveNext from this returned object. If MoveNext returns
true it knows that there is some data to be read and it calls the property Current to access this
data. From Current the get accessor gets called which always returns “hi” in our case. Then
MoveNext gets called and if it returns false, we quit out of the foreach statement. As MoveNext
always returns true, we go into an indefinite loop.

        a.cs
        using System.Collections;
        public class zzz
        {
        public static void Main()
{
yyy f = new yyy();
foreach (string i in f)
{
System.Console.WriteLine(i);
}
}
}
class yyy
{
public IEnumerator GetEnumerator()
{
return new xxx();
}
}
class xxx : IEnumerator
{
public string [] a = new string[3] {“hi” , “bye” ,”no”};
public int i = -1;
public bool MoveNext()
{
i++;
System.Console.WriteLine(“MoveNext” + i);
if ( i == 3)
return false;
else
return true;
}
public void Reset()
{
System.Console.WriteLine(“Reset”);
}
public object Current
{
get
{
System.Console.WriteLine(“Current “ + a[i]);
return a[i];
}
}
}

Output
MoveNext0
Current hi
hi
MoveNext1
Current bye
bye
MoveNext2
Current no
no
MoveNext3
We have created an array a which has 3 members and initialized them respectively to hi, bye and
no by giving the strings in {} immediately after the new. Each time MoveNext gets called the
variable i is increased by 1. If the value of i is 3, we have no more strings to return and thus we
return false, else we return true. The variable i keeps track of how many times the function
MoveNext is being called. As MoveNext returns true, Current gets called which returns a string
from the array using i as the offset. Thus we can iterate through the entire array depending upon
the length.

        a.cs
        using System.Collections;
        public class zzz
        {
        public static void Main()
        {
        yyy f = new yyy(“This is Great”);
        foreach (string i in f)
        {
        System.Console.WriteLine(i);
        }
        }
        }
        class yyy
        {
        string t;
        public yyy(string t1)
        {
        t = t1;
        }
        public IEnumerator GetEnumerator()
        {
        return new xxx(t);
        }
        }
        class xxx : IEnumerator
        {
        public string [] a;
        public xxx(string t3)
        {
        char [] b = new char[1];
        b[0] = ‘ ‘;
        a = t3.Split(b);
        }
        public int i = -1;
        public bool MoveNext()
        {
        i++;
        System.Console.WriteLine(“MoveNext “ + i);
        if ( i == a.Length)
        return false;
        else
        return true;
        }
        public void Reset()
{
       System.Console.WriteLine(“Reset”);
       }
       public object Current
       {
       get
       {
       System.Console.WriteLine(“Current “ + a[i]);
       return a[i];
       }
       }
       }

       Output
       MoveNext 0
       Current This
       This
       MoveNext 1
       Current is
       is
       MoveNext 2
       Current Great
       Great
       MoveNext 3

Pretty big program. At the time of creating a yyy object we are passing a string to the
constructor. Thus the yyy constructor gets called first. The constructor stores this string in
variable t. The foreach statement calls GetEnumerator which now creates a xxx object
passing it the string through t. The constructor of xxx now gets called. Every string class
has a member function called Split. Split will break up a string on certain characters
which we call delimiters. In this case, we want our string to be broken up whenever we
encounter a space. The Split function requires an array of chars which it can use as a
delimiter. The reason it requires an array is because we may have more than one char that
we would like to break the string on. Like earlier, the array a now contains the array of
strings. The last change is the condition in the if statement. Earlier we used a constant
number, now we use a member, Length, of an array which stores the length of the array
or the number of members. Thus the class yyy can now be used as a collection class
which enumerates the individual words in the string. The function Reset for some reason
never ever gets called.

More Related Content

What's hot

Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguageSamir Chekkal
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordKit Eason
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queueecomputernotes
 
Queue data structure
Queue data structureQueue data structure
Queue data structureMekk Mhmd
 
Queue implementation
Queue implementationQueue implementation
Queue implementationRajendran
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
QUEUE IN DATA STRUCTURE USING C
QUEUE IN DATA STRUCTURE USING CQUEUE IN DATA STRUCTURE USING C
QUEUE IN DATA STRUCTURE USING CMeghaj Mallick
 
The Ring programming language version 1.5.3 book - Part 188 of 194
The Ring programming language version 1.5.3 book - Part 188 of 194The Ring programming language version 1.5.3 book - Part 188 of 194
The Ring programming language version 1.5.3 book - Part 188 of 194Mahmoud Samir Fayed
 
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queueSenthil Kumar
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applicationssomendra kumar
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queueAmit Vats
 
Notes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueNotes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueFarhanum Aziera
 
Functions & Recursion
Functions & RecursionFunctions & Recursion
Functions & RecursionNishant Munjal
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Svetlin Nakov
 
The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196Mahmoud Samir Fayed
 
computer notes - Data Structures - 9
computer notes - Data Structures - 9computer notes - Data Structures - 9
computer notes - Data Structures - 9ecomputernotes
 

What's hot (20)

Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
 
Heaps & priority queues
Heaps & priority queuesHeaps & priority queues
Heaps & priority queues
 
Mechanical Engineering Homework Help
Mechanical Engineering Homework HelpMechanical Engineering Homework Help
Mechanical Engineering Homework Help
 
computer notes - Priority queue
computer notes -  Priority queuecomputer notes -  Priority queue
computer notes - Priority queue
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
QUEUE IN DATA STRUCTURE USING C
QUEUE IN DATA STRUCTURE USING CQUEUE IN DATA STRUCTURE USING C
QUEUE IN DATA STRUCTURE USING C
 
The Ring programming language version 1.5.3 book - Part 188 of 194
The Ring programming language version 1.5.3 book - Part 188 of 194The Ring programming language version 1.5.3 book - Part 188 of 194
The Ring programming language version 1.5.3 book - Part 188 of 194
 
My lectures circular queue
My lectures circular queueMy lectures circular queue
My lectures circular queue
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Stacks and queue
Stacks and queueStacks and queue
Stacks and queue
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 
Notes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queueNotes DATA STRUCTURE - queue
Notes DATA STRUCTURE - queue
 
Functions & Recursion
Functions & RecursionFunctions & Recursion
Functions & Recursion
 
05 queues
05 queues05 queues
05 queues
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196
 
computer notes - Data Structures - 9
computer notes - Data Structures - 9computer notes - Data Structures - 9
computer notes - Data Structures - 9
 

Viewers also liked

Csharp_Chap09
Csharp_Chap09Csharp_Chap09
Csharp_Chap09Mohamed Krar
 
Asignatura Infoalfabetizacion
Asignatura InfoalfabetizacionAsignatura Infoalfabetizacion
Asignatura Infoalfabetizacionguestc1475c
 
Nba
NbaNba
Nbaoegiza
 
O Ú L T I M O C A N T O[ R I C A R D O]
O Ú L T I M O  C A N T O[ R I C A R D O]O Ú L T I M O  C A N T O[ R I C A R D O]
O Ú L T I M O C A N T O[ R I C A R D O]guest2c857d
 
Csharp_Chap14
Csharp_Chap14Csharp_Chap14
Csharp_Chap14Mohamed Krar
 
01 Pohledy NejlepĹĄĂ­ Foto 2004
01 Pohledy NejlepĹĄĂ­ Foto 200401 Pohledy NejlepĹĄĂ­ Foto 2004
01 Pohledy NejlepĹĄĂ­ Foto 2004jedlickak01
 
Csharp_Chap15
Csharp_Chap15Csharp_Chap15
Csharp_Chap15Mohamed Krar
 
Csharp_Chap08
Csharp_Chap08Csharp_Chap08
Csharp_Chap08Mohamed Krar
 
Amor
AmorAmor
Amorauricola
 
Csharp_Chap07
Csharp_Chap07Csharp_Chap07
Csharp_Chap07Mohamed Krar
 
Csharp_Chap05
Csharp_Chap05Csharp_Chap05
Csharp_Chap05Mohamed Krar
 
01 Pohledy Suiza
01 Pohledy Suiza01 Pohledy Suiza
01 Pohledy Suizajedlickak01
 

Viewers also liked (15)

Csharp_Chap09
Csharp_Chap09Csharp_Chap09
Csharp_Chap09
 
Asignatura Infoalfabetizacion
Asignatura InfoalfabetizacionAsignatura Infoalfabetizacion
Asignatura Infoalfabetizacion
 
Nba
NbaNba
Nba
 
O Ú L T I M O C A N T O[ R I C A R D O]
O Ú L T I M O  C A N T O[ R I C A R D O]O Ú L T I M O  C A N T O[ R I C A R D O]
O Ú L T I M O C A N T O[ R I C A R D O]
 
Csharp_Chap14
Csharp_Chap14Csharp_Chap14
Csharp_Chap14
 
01 Pohledy NejlepĹĄĂ­ Foto 2004
01 Pohledy NejlepĹĄĂ­ Foto 200401 Pohledy NejlepĹĄĂ­ Foto 2004
01 Pohledy NejlepĹĄĂ­ Foto 2004
 
Curious Things
Curious ThingsCurious Things
Curious Things
 
Csharp_Chap15
Csharp_Chap15Csharp_Chap15
Csharp_Chap15
 
Capacidaddelcerebro
CapacidaddelcerebroCapacidaddelcerebro
Capacidaddelcerebro
 
Csharp_Chap08
Csharp_Chap08Csharp_Chap08
Csharp_Chap08
 
Amor
AmorAmor
Amor
 
Csharp_Chap07
Csharp_Chap07Csharp_Chap07
Csharp_Chap07
 
Csharp_Chap05
Csharp_Chap05Csharp_Chap05
Csharp_Chap05
 
Robotica Valdez
Robotica ValdezRobotica Valdez
Robotica Valdez
 
01 Pohledy Suiza
01 Pohledy Suiza01 Pohledy Suiza
01 Pohledy Suiza
 

Similar to Csharp_Chap13

Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3Jieyi Wu
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdfakkhan101
 
Thread
ThreadThread
Threadphanleson
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressionsLogan Chien
 
Creating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docxCreating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docxR.K.College of engg & Tech
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programsSoumya Behera
 
Prompt a user to enter a series of integers separated by spaces and .pdf
Prompt a user to enter a series of integers separated by spaces and .pdfPrompt a user to enter a series of integers separated by spaces and .pdf
Prompt a user to enter a series of integers separated by spaces and .pdfFootageetoffe16
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Java generics
Java genericsJava generics
Java genericsHosein Zare
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)Tak Lee
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
 
import java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfimport java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfoptokunal1
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginnersishan0019
 
JAVA Question : Programming Assignment
JAVA Question : Programming AssignmentJAVA Question : Programming Assignment
JAVA Question : Programming AssignmentCoding Assignment Help
 

Similar to Csharp_Chap13 (20)

Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
Thread
ThreadThread
Thread
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 
Creating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docxCreating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docx
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Prompt a user to enter a series of integers separated by spaces and .pdf
Prompt a user to enter a series of integers separated by spaces and .pdfPrompt a user to enter a series of integers separated by spaces and .pdf
Prompt a user to enter a series of integers separated by spaces and .pdf
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java generics
Java genericsJava generics
Java generics
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
import java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfimport java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdf
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Oop lecture9 13
Oop lecture9 13Oop lecture9 13
Oop lecture9 13
 
JAVA Question : Programming Assignment
JAVA Question : Programming AssignmentJAVA Question : Programming Assignment
JAVA Question : Programming Assignment
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 

More from Mohamed Krar

Csharp_Contents
Csharp_ContentsCsharp_Contents
Csharp_ContentsMohamed Krar
 
Csharp_Intro
Csharp_IntroCsharp_Intro
Csharp_IntroMohamed Krar
 
Csharp_Chap12
Csharp_Chap12Csharp_Chap12
Csharp_Chap12Mohamed Krar
 
Csharp_Chap11
Csharp_Chap11Csharp_Chap11
Csharp_Chap11Mohamed Krar
 
Csharp_Chap10
Csharp_Chap10Csharp_Chap10
Csharp_Chap10Mohamed Krar
 
Csharp_Chap06
Csharp_Chap06Csharp_Chap06
Csharp_Chap06Mohamed Krar
 
Csharp_Chap04
Csharp_Chap04Csharp_Chap04
Csharp_Chap04Mohamed Krar
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03Mohamed Krar
 
Csharp_Chap02
Csharp_Chap02Csharp_Chap02
Csharp_Chap02Mohamed Krar
 
Csharp_Chap01
Csharp_Chap01Csharp_Chap01
Csharp_Chap01Mohamed Krar
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Csharp In Detail Part1
Csharp In Detail Part1Csharp In Detail Part1
Csharp In Detail Part1Mohamed Krar
 

More from Mohamed Krar (12)

Csharp_Contents
Csharp_ContentsCsharp_Contents
Csharp_Contents
 
Csharp_Intro
Csharp_IntroCsharp_Intro
Csharp_Intro
 
Csharp_Chap12
Csharp_Chap12Csharp_Chap12
Csharp_Chap12
 
Csharp_Chap11
Csharp_Chap11Csharp_Chap11
Csharp_Chap11
 
Csharp_Chap10
Csharp_Chap10Csharp_Chap10
Csharp_Chap10
 
Csharp_Chap06
Csharp_Chap06Csharp_Chap06
Csharp_Chap06
 
Csharp_Chap04
Csharp_Chap04Csharp_Chap04
Csharp_Chap04
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
Csharp_Chap02
Csharp_Chap02Csharp_Chap02
Csharp_Chap02
 
Csharp_Chap01
Csharp_Chap01Csharp_Chap01
Csharp_Chap01
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Csharp In Detail Part1
Csharp In Detail Part1Csharp In Detail Part1
Csharp In Detail Part1
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Recently uploaded (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Csharp_Chap13

  • 1. 13 Collection Objects Earlier we used an array in a foreach. If the array had three members, the foreach got executed three times and each time the variable i had a different value. The concept described below is called a collection class. It is a class that returns a value each time till the values run out, thus making it easier for us to iterate through the array. a.cs public class zzz { public static void Main() { yyy f = new yyy(); foreach (string i in f) { } } } class yyy { } Compiler Error a.cs(6,1): error CS1579: foreach statement cannot operate on variables of type ‘yyy’ because ‘yyy’ does not contain a definition for ‘GetEnumerator’, or it is inaccessible To use yyy in a foreach as a collection class, foreach requires a function GetEnumerator. a.cs public class zzz { public static void Main() { yyy f = new yyy(); foreach (string i in f) { } } } class yyy
  • 2. { public int GetEnumerator() { } } Compiler Error a.cs(6,1): error CS1579: foreach statement cannot operate on variables of type 'yyy' because 'int' does not contain a definition for 'MoveNext', or it is inaccessible a.cs(13,12): error CS0161: 'yyy.GetEnumerator()': not all code paths return a value Foreach obviously tries to execute the function called GetEnumerator. This function should not return an int but something else as the error suggests. a.cs using System.Collections; public class zzz { public static void Main() { yyy f = new yyy(); foreach (string i in f) { } } } class yyy { public IEnumerator GetEnumerator() { return new xxx(); } } class xxx : IEnumerator { } Compiler Error a.cs(19,7): error CS0535: ‘xxx’ does not implement interface member ‘System.Collections.IEnumerator.MoveNext()’ a.cs(19,7): error CS0535: ‘xxx’ does not implement interface member ‘System.Collections.IEnumerator.Reset()’ a.cs(19,7): error CS0535: ‘xxx’ does not implement interface member ‘System.Collections.IEnumerator.Current’ IEnumerator is an interface which has three functions MoveNext, Reset and Current and xxx has to implement all of them to remove the compiler errors. a.cs using System.Collections;
  • 3. public class zzz { public static void Main() { yyy f = new yyy(); foreach (string i in f) { System.Console.WriteLine(i); } } } class yyy { public IEnumerator GetEnumerator() { return new xxx(); } } class xxx : IEnumerator { public bool MoveNext() { System.Console.WriteLine(“MoveNext”); return true; } public void Reset() { System.Console.WriteLine(“Reset”); } public object Current { get { System.Console.WriteLine(“Current”); return “hi”; } } } Run the program and you will notice that the output does not stop. It goes on forever. IEnumerator is an interface which belongs to the namespace System.Collections. foreach first calls the function GetEnumerator from yyy. It expects this function to return an object like IEnumerator. It then calls the function MoveNext from this returned object. If MoveNext returns true it knows that there is some data to be read and it calls the property Current to access this data. From Current the get accessor gets called which always returns “hi” in our case. Then MoveNext gets called and if it returns false, we quit out of the foreach statement. As MoveNext always returns true, we go into an indefinite loop. a.cs using System.Collections; public class zzz { public static void Main()
  • 4. { yyy f = new yyy(); foreach (string i in f) { System.Console.WriteLine(i); } } } class yyy { public IEnumerator GetEnumerator() { return new xxx(); } } class xxx : IEnumerator { public string [] a = new string[3] {“hi” , “bye” ,”no”}; public int i = -1; public bool MoveNext() { i++; System.Console.WriteLine(“MoveNext” + i); if ( i == 3) return false; else return true; } public void Reset() { System.Console.WriteLine(“Reset”); } public object Current { get { System.Console.WriteLine(“Current “ + a[i]); return a[i]; } } } Output MoveNext0 Current hi hi MoveNext1 Current bye bye MoveNext2 Current no no MoveNext3
  • 5. We have created an array a which has 3 members and initialized them respectively to hi, bye and no by giving the strings in {} immediately after the new. Each time MoveNext gets called the variable i is increased by 1. If the value of i is 3, we have no more strings to return and thus we return false, else we return true. The variable i keeps track of how many times the function MoveNext is being called. As MoveNext returns true, Current gets called which returns a string from the array using i as the offset. Thus we can iterate through the entire array depending upon the length. a.cs using System.Collections; public class zzz { public static void Main() { yyy f = new yyy(“This is Great”); foreach (string i in f) { System.Console.WriteLine(i); } } } class yyy { string t; public yyy(string t1) { t = t1; } public IEnumerator GetEnumerator() { return new xxx(t); } } class xxx : IEnumerator { public string [] a; public xxx(string t3) { char [] b = new char[1]; b[0] = ‘ ‘; a = t3.Split(b); } public int i = -1; public bool MoveNext() { i++; System.Console.WriteLine(“MoveNext “ + i); if ( i == a.Length) return false; else return true; } public void Reset()
  • 6. { System.Console.WriteLine(“Reset”); } public object Current { get { System.Console.WriteLine(“Current “ + a[i]); return a[i]; } } } Output MoveNext 0 Current This This MoveNext 1 Current is is MoveNext 2 Current Great Great MoveNext 3 Pretty big program. At the time of creating a yyy object we are passing a string to the constructor. Thus the yyy constructor gets called first. The constructor stores this string in variable t. The foreach statement calls GetEnumerator which now creates a xxx object passing it the string through t. The constructor of xxx now gets called. Every string class has a member function called Split. Split will break up a string on certain characters which we call delimiters. In this case, we want our string to be broken up whenever we encounter a space. The Split function requires an array of chars which it can use as a delimiter. The reason it requires an array is because we may have more than one char that we would like to break the string on. Like earlier, the array a now contains the array of strings. The last change is the condition in the if statement. Earlier we used a constant number, now we use a member, Length, of an array which stores the length of the array or the number of members. Thus the class yyy can now be used as a collection class which enumerates the individual words in the string. The function Reset for some reason never ever gets called.