How To Add Interface Ienumerable To Templated Class
Introduction
The IEnumerable interface is the base Interface for many collections in C#, and its job is to provide a mode of iteration through a collection. That is why we tin utilize for each loops to go through a List or a Lexicon. In simple English when a collection class implements the IEnumerable interface it becomes countable, and we can count each element in it individually
There are 2 versions of the IEnumerable Interface
1.IEnumerable <T> for generic collections
two.IEnumerable for nongeneric collections
But since generic collections were introduced after after the non-generic ones and it is no longer recommended to employ the non-generic collections in a new project due to their need to perform boxing and unboxing (converting the types of objects), we volition explicate how to use the
IEnumerable <T> interface in this lesson
IEnumerable<T> contains a single method that you must implement when implementing this interface; GetEnumerator(), which returns an IEnumerator<T> object. The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property that points at the object we are currently at in the drove.
IEnumerables accept a method to get the next particular in the collection, so they look at items "one at a time," they don't need the whole collection to be in memory. They don't know how many items are in it for each loop. Information technology but keeps getting the next item until it runs out. IEnumerables besides aid ensure immutability (read-just)
when information technology is recommended to apply the IEnumerable interface:
- Your collection represents a massive database table, you don't want to copy the entire matter into memory and cause performance issues in your application.
When it is not recommended to employ the IEnumerable interface:
- You lot need the results right abroad and are mayhap mutating/editing the objects after on. In this case, it is better to use an Array or a List
Making your Classes Enumerable
In this case, we will see how to brand our course Enumerable meaning we can use an instance of it inside a for each loop
let'due south consider the post-obit classes
Class 1: a class chosen dog which has two properties
- string Name
- bool IsNaughtyDog
and ane method
- GiveTreat() which volition cause the dog to say "wuf" on the console :)
| //a course named Domestic dog which we volition apply in some other class called DogShelter which volition contain a drove of this class public string Name { get ; set ; } public bool IsNaughtyDog { get ; set ; } public Dog ( cord name , bool isNaughtyDog ) { this . IsNaughtyDog = isNaughtyDog ; //this method will print how many treats the dog received public void GiveTreat ( int numberofTreats ) { //print a message containing the number of treats and the name of the domestic dog Panel . WriteLine ( "Dog: {0} said wuoff {1} times!." , Name , numberofTreats ) ; |
Class 2: a grade chosen DogShelter
Which contains the List of dogs and that'due south it
The List of dogs is initialized in the constructor
| //a class named DogShelter this class contains a generic collection of type Domestic dog //objects of this course can't be used inside a for each loop because it lacks an implementation of the IEnumerable interface //list of type List<Dog> public List & lt ; Canis familiaris & gt ; dogs ; //this constructor volition initialize the dogs list with some values //initialize the dogs list using the drove-initializer dogs = new Listing & lt ; Dog & gt ; ( ) { |
Now in the main method let's create a new DogShelter object and try to Enumerate through information technology
using a for each loop
| using System . Collections . Generic ; namespace IEnumerableandIEnumerator { static void Main ( cord [ ] args ) { //create a new object of type DogShelter DogShelter shelter = new DogShelter ( ) ; //for each dog in the DogShelter object foreach ( Dog dog in shelter ) { //fault because the DogShelter class does't implement the IEnumerable interface nonetheless //if the dog is non naughty (good boy) //too give treats :) merely only 1 |
We will Immediately see an fault , This error is proverb that our class lacks the ability to be Enumerated through
To fix this we demand to implement the interface IEnumerbale<T> where T is going to be the type of objects that we will enumerate through which in our instance is Dog
first, since this interface is concerned with the generic collections, we demand to import the generic collections namespace
after nosotros implement the interface IEnumerable<Dog> our class should look similar this
| class DogShelter : IEnumerable & lt ; Dog & gt ; { // error considering this course doesn't provide it'south implementation of the methods from the IEnumerable interface //listing of type Listing<Dog> public List & lt ; Domestic dog & gt ; dogs ; //this constructor will initialize the dogs list with some values //initialize the dogs list using the collection-initializer dogs = new Listing & lt ; Dog & gt ; ( ) { |
Now the mistake within the for each loop is gone, but another fault has appeared on the IEnumerable<Domestic dog>
Information technology is lament considering we did not implement the ii methods that are inside the IEnumerable Interface, which are
- IEnumerable<Dog>.GetEnumerator() which is the method nosotros need to implement to make our class Enumerable.
- IEnumerable.GetEnumerator() which is the non-generic version of the get-go method
Now the reason we need to implement the second method (non-generic version) is to ensure backward compatibility with the non-generic collections just in instance because the generic collections came after the not-generic collections
Let's striking testify potential fixes
and then select Implement Interface
These will the 2 methods we mentioned above in our class
The course should look like this afterward
| course DogShelter : IEnumerable & lt ; Dog & gt ; { //list of type List<Dog> public Listing & lt ; Domestic dog & gt ; dogs ; //this constructor will initialize the dogs listing with some values //initialize the dogs listing using the collection-initializer dogs = new List & lt ; Canis familiaris & gt ; ( ) { //this method will get generated for us //we will apply this method to provide implementation to the GetEnumerator() method of the IEnumerator interface public IEnumerator & lt ; Dog & gt ; GetEnumerator ( ) { throw new NotImplementedException ( ) ; //this method volition get generated for usa //since in this example nosotros won't exist passing our class to a non-generic method nosotros don't need to provide an implementation for it at this bespeak IEnumerator IEnumerable . GetEnumerator ( ) { throw new NotImplementedException ( ) ; |
Now since generic collections implement the IEnumerable Interface, then they also have their ain implementation of the GetEnumerator() method, Which means in our instance since the DogShelter uses a Listing<Dog> every bit a collection then we can utilize the GetEnumerator() of that list equally a workaround
Our DogShelter course should then expect like this
| class DogShelter : IEnumerable & lt ; Dog & gt ; { //listing of blazon Listing<Canis familiaris> public Listing & lt ; Dog & gt ; dogs ; //this constructor will initialize the dogs listing with some values //initialize the dogs list using the collection-initializer dogs = new List & lt ; Dog & gt ; ( ) { //this method volition go generated for us //we will use this method to provide implementation to the GetEnumerator() method of the IEnumerator interface public IEnumerator & lt ; Domestic dog & gt ; GetEnumerator ( ) { //since our listing of dogs is a generic collection that already implements its own IEnumerable interface render dogs . GetEnumerator ( ) ; //this method will become generated for u.s. //since in this example nosotros won't be passing our class to a non-generic method we don't need to provide an implementation for it at this point IEnumerator IEnumerable . GetEnumerator ( ) { throw new NotImplementedException ( ) ; |
Complete Code
| using Arrangement . Collections . Generic ; namespace IEnumerableandIEnumerator { static void Primary ( string [ ] args ) { //create a new object of type DogShelter DogShelter shelter = new DogShelter ( ) ; //for each dog in the DogShelter object foreach ( Dog dog in shelter ) { //error because the DogShelter class does't implement the IEnumerable interface still //if the domestic dog is not naughty (skilful male child) //also give treats :) merely simply 1 //a grade named Domestic dog which we will use in another form called DogShelter which will contain a collection of this class public string Name { get ; fix ; } public bool IsNaughtyDog { get ; set ; } public Dog ( string name , bool isNaughtyDog ) { this . IsNaughtyDog = isNaughtyDog ; //this method will impress how many treats the dog received public void GiveTreat ( int numberofTreats ) { //impress a message containing the number of treats and the proper name of the dog Console . WriteLine ( "Dog: {0} said wuoff {i} times!." , Name , numberofTreats ) ; form DogShelter : IEnumerable & lt ; Dog & gt ; { //list of type List<Dog> public Listing & lt ; Dog & gt ; dogs ; //this constructor will initialize the dogs list with some values //initialize the dogs list using the collection-initializer dogs = new List & lt ; Dog & gt ; ( ) { //this method will get generated for usa //we will employ this method to provide implementation to the GetEnumerator() method of the IEnumerator interface public IEnumerator & lt ; Dog & gt ; GetEnumerator ( ) { //since our list of dogs is a generic collection that already implements its own IEnumerable interface return dogs . GetEnumerator ( ) ; //this method volition become generated for us //since in this example nosotros won't be passing our class to a non-generic method nosotros don't need to provide an implementation for it at this signal IEnumerator IEnumerable . GetEnumerator ( ) { throw new NotImplementedException ( ) ; |
How To Add Interface Ienumerable To Templated Class,
Source: https://tutorials.eu/ienumerable-and-ienumerator/
Posted by: frazieryounly.blogspot.com

0 Response to "How To Add Interface Ienumerable To Templated Class"
Post a Comment