C# IEnumerable Interface

implementation of IEnumerable Interface in C#

IEnumerable is the implementation of the iterator pattern and is used to give the ability to iterate a class without knowing its internal structure. This Interface exposes the enumerator, which supports a simple iteration over a collection of a specified type. When a class implements IEnumerable, it can be enumerated. This means you can use a foreach block to iterate over that type. In C# all collections implements this interface.

Here is example of foreach loop iterates over the IEnumerable<int>.

class Program
{
    static void Main()
    {
	IEnumerable<int> result = from value in Enumerable.Range(1, 6)select value;
				
	foreach (int value in result)
	{
	    Console.WriteLine(value);
	}

    }
}

This interface is used with Yield Return key phrase, You can find more about it here.

Implementation

In this example, Test Class contains array of Test items. WE need to provide implementation of  GetEnumerator() that returns IEnemerator.

class Test : IEnumerable
    {
        Test[] Items = null;
        int freeIndex = 0;
        public string Name { get; set; }
        public int Id { get; set; }

        public Test()
        {
            Items = new Test[5];
        }

    public void Add(Test item)
    {
        Items[freeIndex] = item;
        freeIndex++;
    }

//implementation of IEnumerator
    public IEnumerator GetEnumerator()
    {
        foreach (object o in Items)
        {
            if(o == null)
                break;
            yield return o;
        }
    }
    }
    class Program
        {
            public static void Main(String[] args)
            {
                Test t1 = new Test();
                t1.Name = "Bob";
                t1.Id = 0;

                Test t2 = new Test();
                t2.Name = "John";
                t2.Id= 1;

                Test myList = new Test();
                myList.Add(t1);
                myList.Add(t2);

//Now we can use for each loop
                foreach (Test obj in myList)
                {
                   Console.WriteLine("Name: "+ obj.Name + "Id:- "+ obj.Id);
                }
                Console.ReadLine();
            }
        }

 

This is just basic introduction to this subject, for each loop is a syntax sugar. There is much more happening in the background. This post is starting point to this subject, in next article I’ll cover more advanced topics. Stay Awesome!

 

 

C# Yield Return

C# Yield Return key-phrase, explained with examples.

Yield return key-phrase that is used to return a value of the collection instead of  returning the full list. It can be explained with example of watching a video. Yield is like streaming the video, while typical implementation is like downloading it. This phrase interacts with foreach loop, it iterates through collection of items, returns an item and gets called over and over again, but each time it resumes execution where it left off. It’s easier to read, and can have better performance than typical implementation.

In this example we have typical list and we iterate through it to find the results we are looking for, this is an example of Customized iteration through a collection.



static void Main(string[] args) 
{
//We create en empty list
List<int> NewList = new List<int>();
//We add few items
    NewList.Add(1);
    NewList.Add(2);
    NewList.Add(3);
    NewList.Add(4);
    NewList.Add(5);
//Iterates through list, and displays the values 
    foreach (int i in NewList) 
    {
          Console.WriteLine(i);
    }
}

You can find more about list in my post dedicated to it, here.

Now lets crate a method that find the values

static IList<int> FindGraterthan4(List<int> list)
{
     var tempList = new List<int>();

     foreach (var value in list)
     {
         if (value >= 4)
          tempList.Add(value);
      }

    return tempList;
 }

This way we create a new List(IList) we can iterate through to print results. We add this code to main method.

  IList<int> TempList=FindGraterthan4(NewList);
  foreach (int i in TempList)
  {
      Console.WriteLine(i);
  }

New lets create the same thing with Yield Return

 static IEnumerable<int> FindWithYR(List<int> list)
 {
     foreach (var value in list)
     {
         if (value >= 4)
             yield return value;
     }
 }

We can iterate through this with for each loop

foreach (int i in FindWithYR(NewList))
 {
     Console.WriteLine(i);
 }

WE have the same result with less amount of code and better performance. This was just example of program that uses this phrase, In the future I’ll writhe article about the process that is happening in the background. In my next article I’ll cover the topic of IEnumerable interface. Stay Awesome!

 

 

 

Interfaces

interface implementation in c# .net

In post about abstraction abstract classes I used examples of method which  implementation is defined in derived class. Here is when Interfaces comes in play.  An interface contains only the signatures(declarations) of methods, properties, events or indexers. It looks like a class, but has no implementation. The reason interfaces only provide declarations is because they are inherited by classes and structs, which must provide an implementation for each interface member declared. It’s important to add that  Class can inherit from multiple interfaces, but not multiple classes.

Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way.

Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default.  Interface declaration should have “I” prefix, it is programming habit, that informs user that this is not a class or anything else just by looking at its name:

public interface INewInterface
{
// interface members, public as default. Interfaces does not allow 
//explicit access modifiers. 
   void Print();
   double getNumber();
}

This is simple example of interface it does not contains any implementations. That’s why we need to provide it in derived class. Method signature must be the same in both cases.

  • Interface can not contain fields

 

 
   public class MyClass : INewInterface
   {
      private double number;
//class constructor
      public MyClass()
      {
         number = 25.6;
      }
      public double getNumber()
      {
         return number;
      }
      
      public void Print()
      {
         Console.WriteLine("Transaction: {0}", number);
      }
   }

 

Here we provided the implementation of the methods, all signatures matches the Interface signatures, we can add fields and new methods in this class. This class must provide implementation of all methods, methods in interface inheritance chains as well.

 

class MainClass
   {
      static void Main(string[] args)
      {
         MyClass n1 = new MyClass();
         n1.Print();
         Console.ReadKey();
      }
   }

 

Now we create instance of our class and execute the methods. Now you know entire  process of interface implementation, it’s worth to remember that class can inherit multiple  interfaces, and that we can not instantiate instance  of an interface. In next topic We will take a look at the differences between interfaces and abstract classes. Stay Awesome!