Monday, May 7, 2012

AOP : Aspect Oriented Programming Basic

What is AOP?

Aspect Oriented Programming or AOP is an interesting concept that can be applied to many of the programming problems we solve everyday. In our Visual Studio team system code we have a lot of web-services and remoting code that essentially does the following
public void MyMethod(int parameter)
{
    Trace.EnteredMethod("MyMethod", parameter);
    SecurityCheck();
    // Bunch of processing
    Trace.ExitMethod("MyMethod");
}
This is not just peculiar to our domain but is seen across different domains. In OO programming classes and methods are designed for performing specific operations and common/duplicate functionality are factored out into common classes. However, there are cross-cutting concerns that span accross all classes and methods, like logging and security checks. OOP only partially solves this problem by requiring users to define separate classes for logging and security checks and requiring each class/methods needing these services to call them. AOP targets and solves this problem elegantly.
AOP divides code into base-code (code for your functionality) and a new construct called aspect. Aspect encapsulates these cross-cutting concerns using the following concepts
  • join-points: The points in the structure of base-code where the cross-cutting functionality needs to execute. This is typically when specific methods are entered or exited or properties are accessed.
  • point-cut: A logical description of join-points using some specific syntax
  • advice: additional code like logging and security check that each of these methods need to perform
The most mature AOP language is probably AspectJ which adds AOP extensions to Java. However, for this blog, I'd stick to .NET languages like AspectDNG, Aspect# and C#.


There is a lot of AOP implementation in C#, VB.net. this is some of AOP Implementations:
  • Aspect.NET
  • LOOM.NET
  • Enterprise Library 3.0 Policy Injection Application Block
  • Puzzle.NAspect
  • AspectDNG
  • Aspect#
  • Compose*
  • PostSharp
  • Seasar.NET
  • DotSpect (.SPECT)
  • The Spring.NET Framework as part of its functionality
  • Wicca and Phx.Morph
  • SetPoint
Another Article:

Index

Introduction

I just completed my second book ".NET Interview questions" and now on my third book "SQL Server 2005 Interview questions". Had a decent time in between to update my skills and be in tune with new developments. Thanks to my publisher for giving me a free pass for the Aspect Oriented Programming seminar in Mumbai, that's what has inspired me to write this article. A lot has been written about AOP (Aspect Oriented Programming) on the Web, but none of the articles cover how to implement it practically in C#.
Let's start with a small definition on AOP first:
"Aspect Oriented Programming is a methodology to separate cross cut code across different modules in a software system."
In short all the cross cut code is moved to a separate module, thus increasing more modularity and bringing in ease of maintenance. Okay, that was a theoretical definition, let's try to understand why we really need AOP when we have decent methodologies like "Object Oriented Programming" and "Procedural Oriented Programming".
"Aspect oriented programming is not introduced in order to replace OOP, but assists it to remove its short comings. I see AOP as a brother of OOP".

Every requirement is a Concern

"Software development exists because of business concerns".
Software development is nothing but addressing a collection of concerns in real life. For instance, a customer sales software application has the following concerns:
  • User should be able to add, update and delete customer related information.
  • User should be able to track sales related to customer.
  • User should have a facility to print customer and sales information.
  • User should have a facility to email customer and sales information.
Okay, now readers will be wondering what's so special about these concerns, it can easily be implemented using OOP. In the next section we will try to implement the above concerns using the OOP methodology and see why we need AOP.

Cross Cutting Concern and Tangled code

Figure 1.1 Class diagram for Customer Sales Software Application
Above is the class diagram for the Customer Sales Software Application discussed in the first section. We are trying to address the four concerns for the application: Customer Maintenance, Sales Maintenance, Printing and Sending Email. So by abiding to all laws of OOP, the above class diagram is drawn. "ClsCustomer" class is responsible for adding, updating and deleting the customer records. "ClsSales" class is responsible for maintaining sales information for a customer, you can see the link between "ClsCustomer" and "ClsSales" classes. There were also some technical concerns. Printing and sending email are addressed by "ClsPrint" and "ClsEmail" classes. Also note both classes "ClsCustomer" and "ClsSales" have a dependency relationship on both of these classes ("ClsPrint" and "ClsEmail") to achieve the technical functionality.
Now according to OOP literature the first very important thing is that every object should be independent and should be concerned only about its functionality. Example, the "ClsCustomer" should only be concerned about adding, updating and deleting customer records. The Customer class should not have responsibilities of Sales or Print class. All the objects should work using messaging to achieve certain business functionality. In the above class diagram, all the classes are collaborating to make work the complete "Customer Sales Application".
OK, now it's time to look at the implementation of the above class diagram.
Figure 1.2 Explorer look of Customer Sales Application
As dictated by the class diagram, all the classes are included in the Explorer. OK, let's look at one of the implementations, that is the customer class implementation, i.e. the "Add" method of the Customer class. Below is a paste of the "Add" method of the Customer class.
public void Add()
{
  /////////////////////////////////////////
  // This method adds customer information
  // 
  // Adding code will go here
  ////////////////////////////////////////

  // After adding to database email is sent
  ClsEmail pobjClsEmail = new ClsEmail();
  pobjClsEmail.Send();

  // After sending email its printed
  ClsPrint pobjClsPrint = new ClsPrint();
  pobjClsPrint.Print();
}
Okay, the "Add" method of "ClsCustomer" is doing some really heavy duty like:
  • It adds the customer data to the customer database.
  • Then it sends email using the class "ClsEmail".
  • Finally it prints the customer details using the "ClsPrint" class.
Don't you think guys "ClsCustomer" is doing some really heavy job, specially it's doing a lot of things which is not its concern. Example: sending email and printing is not its concern at all. Also note the same implementation has to be done with the "ClsSales" class. So in the Sales class also, we have to use both the classes: "ClsEmail" and "ClsPrint". In short the "Print" and "Email" span across more than one module. Such types of concerns are called as "Cross Cut Concerns". The code over there is quiet messed up as we are using lots of objects. These types of code are called as "Tangled code" in AOP terminology.
Okay, so here are some observations about concerns. All software applications have two types of concerns:
  • Core / Main concern. (Example: Customer and Sales maintenance concerns).
  • Cross cut concerns. (Printing, logging, sending email etc. which spans across modules).
Now we are aware of our problem "tangled code".

Solution for Tangled code: Weaving

Simply separate the Cross cut concerns from the Core concerns. So create modules for Cross cut and Core Concerns separately and then feed both the modules to the compiler. AOP supported compilers then compile both the modules and generate one single executable......isn't that cool guys? Hmmm.. now how do we attain that with .NET compilers? Well, till now .NET compilers did not support actual AOP compiling. So we had to do quiet a hack to attain AOP functionality in .NET. AspectJ is an AOP compiler which does AOP implementation for Java. But I hope the way .NET framework is architected it should not be a big deal to get AOP to action....can you hear me Microsoft, we trust you.
"Weaving is a process of compiling the Core and Cross cut concerns together".
Figure 1.3 AOP weaver in action
In the coming sections, we will try to see the different kinds of weavers documented for AOP. Let us see which type of weaving can we implement in C#. But for now, let's try to understand some basic terminology which you will come across again and again.

Join points, Point cuts and Advice

Join points, Point cuts and Advice are some basics which you will need to understand for AOP.
Join point is a point where a concern will cross cut the main code. Join points can be a method call, function, constructor etc. Join points are useful in identifying problem points in a code. In our customer sales application, we have two join points:
  • pobjClsEmail.Send();
  • pobjClsPrint.Print();
Point Cut tells when it should match a Joint Point. In the above example I can say to match the email join point only when it's called in conjunction with "Invoke". Example:
Invoke( pobjClsEmail.Send(); )
So I have defined my point cut with the Email joint point using the Invoke method.
Advice when defined decides the sequence of execution of advice code with respect to joint point. Advice code is the code which you want to execute before or after the joint point. In AOP you can specify the advice code to execute before, around or after the joint point is matched.
Note: Whatever is the case before, after or around, point cut must trigger first.
So depending on what you have specified, the advice code will execute before, after or around the joint point. Like in our example we will want to execute the send and print afterwards.

Types of AOP compilers

OK, AOP compilers come in different flavors and the type of weaving decides what type of compiler it is. There are four types of compilers, or to be specific, weaving types in AOP:
  • Compile time weaving: This type of weaving happens at the compiler level and is not supported currently in .NET. But there are other compilers which I will discuss in my next part of the AOP tutorial. In compile time, Core concern code and the Cross cut code is weaved before being compiled to MSIL code. So before the JIT compilation takes place, using .NET compilers Aspect code is compiled and fed to the main compiler. There are many third party compilers which are available which extend the .NET compiler module and implement this feature. I am sure when Microsoft implements this feature in .NET compilers......it's going to be party time guys.
  • Link time weaving: This type of compilers compile core and cross cut code after the MSIL is generated. Again this has to be done at linker level. So at this moment not supported, we will either have to use third party or wait for Microsoft's AOP compiler.
  • Run time weaving: This type of weaving is done by using the .NET runtime. In short your code detects the Core, Cross cut etc. and executes them at run time. This is supported at this moment in .NET and we will see how we can implement Run time weaving. Again many AOP gurus do argue that it is not actual AOP.... I leave that to the readers.
From my point of view, compiler is AOP featured when it has keyword support for Aspect, Join points, Point cut, Advice etc. So till then .NET guys can go around using the round about methods (which I will explain in the second part) to claim that .NET is AOP featured.
I hope I was able to explain the fundamentals of AOP. In the second part of this tutorial, we will see how we can implement the above AOP features in .NET.
OK guys, just a short note: do give me a feedback on my collection of .NET Interview questions on my website.

Microsoft : Enterprise Library 5.0

Overview

Enterprise Library consists of reusable software components that are designed to assist developers with common enterprise development challenges. It includes a collection of functional application blocks addressing specific cross-cutting concerns such as data access, logging, or validation; and wiring blocks, Unity and the Interception/Policy Injection Application Block, designed to help implement more loosely coupled testable, and maintainable software systems.
Different applications have different requirements, and you will find that not every application block is useful in every application that you build. Before using an application block, you should have a good understanding of your application requirements and of the scenarios that the application block is designed to address. Note that this release of the Enterprise Library includes a selective installer that allows you to choose which of the blocks you wish to install.
Microsoft Enterprise Library 5.0 contains the following application blocks:
  • Caching Application Block. Developers can use this application block to incorporate a cache in their applications. Pluggable cache providers and persistent backing stores are supported.
  • Cryptography Application Block. Developers can use this application block to incorporate hashing and symmetric encryption in their applications.
  • Data Access Application Block. Developers can use this application block to incorporate standard database functionality in their applications, including both synchronous and asynchronous data access and returning data in a range of formats.
  • Exception Handling Application Block. Developers and policy makers can use this application block to create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.
  • Logging Application Block. Developers can use this application block to include logging functionality for a wide range of logging targets in their applications. This release further improves logging performance.
  • Policy Injection Application Block. Powered by the Interception mechanism built in Unity, this application block can be used to implement interception policies to streamline the implementation of common features, such as logging, caching, exception handling, and validation, across a system.
  • Security Application Block. Developers can use this application block to incorporate authorization and security caching functionality in their applications.
  • Unity Application Block. Developers can use this application block as a lightweight and extensible dependency injection container with support for constructor, property, and method call injection, as well as instance and type interception.
  • Validation Application Block. Developers can use this application block to create validation rules for business objects that can be used across different layers of their applications.
Enterprise Library also includes a set of core functions, including configuration and instrumentation, and object lifecycle management. These functions are used by all other application blocks.

Design Pattern : Command patterns Implementation

Command pattern allows a request to exist as an object. Ok let’s understand what it means. Consider the figure ‘Menu and Commands’ we have different actions depending on which menu is clicked. So depending on which menu is clicked we have passed a string which will have the action text in the action string. Depending on the action string we will execute the action. The bad thing about the code is it has lot of ‘IF’ condition which makes the coding more cryptic.
Figure: - Menu and Commands
Command pattern moves the above action in to objects. These objects when executed actually execute the command.
As said previously every command is an object. We first prepare individual classes for every action i.e. exit, open, file and print. Al l the above actions are wrapped in to classes like Exit action is wrapped in ‘clsExecuteExit’ , open action is wrapped in ‘clsExecuteOpen’, print action is wrapped in ‘clsExecutePrint’ and so on. All these classes are inherited from a common interface ‘IExecute’.
Figure: - Objects and Command
Using all the action classes we can now make the invoker. The main work of invoker is to map the action with the classes which have the action.
So we have added all the actions in one collection i.e. the arraylist. We have exposed a method ‘getCommand’ which takes a string and gives back the abstract object ‘IExecute’. The client code is now neat and clean. All the ‘IF’ conditions are now moved to the ‘clsInvoker’ class.

Figure: - Invoker and the clean client

Example 2

Our implementation.

Sample Code

BaseCommand is abstract base class used to define contract.

  1. public abstract class BaseCommand  
  2. {  
  3.         protected Transaction _transaction;  
  4.   
  5.         public abstract int Execute(Transaction transaction);  
  6.   
  7.         public abstract int Undo();  
  8. }  
ConcreteCommandDeposit and ConcreteCommandWithdraw are the concrete command as well as Receiver classes.

  1. public class ConcreteCommandDeposit : BaseCommand  
  2. {  
  3.         #region Command Members  
  4.   
  5.         public override int Execute(Transaction transaction)  
  6.         {  
  7.             this._transaction = transaction;  
  8.             _transaction.BalanceAmount += _transaction.Amount;  
  9.             return _transaction.BalanceAmount;  
  10.         }  
  11.   
  12.         public override int Undo()  
  13.         {  
  14.             _transaction.BalanceAmount -= _transaction.Amount;  
  15.             return _transaction.BalanceAmount;  
  16.         }  
  17.  
  18.         #endregion  
  19. }  

  1. public class ConcreteCommandWithdraw : BaseCommand  
  2. {  
  3.         #region Command Members  
  4.   
  5.         public override int Execute(Transaction transaction)  
  6.         {  
  7.             this._transaction = transaction;  
  8.             _transaction.BalanceAmount -= _transaction.Amount;  
  9.             return _transaction.BalanceAmount;  
  10.         }  
  11.   
  12.         public override int Undo()  
  13.         {  
  14.             _transaction.BalanceAmount += _transaction.Amount;  
  15.             return _transaction.BalanceAmount;  
  16.         }  
  17.  
  18.         #endregion  
  19. }  
CommandInvoker class encapsulates call to command object and used to invoke command.

  1. public class CommandInvoker  
  2. {  
  3.         private BaseCommand _Command { getset; }  
  4.          
  5.         public CommandInvoker(BaseCommand command)  
  6.         {  
  7.             this._Command = command;  
  8.         }  
  9.   
  10.         public int ExecuteCommand(Transaction param)  
  11.         {  
  12.             return _Command.Execute(param);  
  13.         }  
  14.   
  15.         public int UndoCommand()  
  16.         {  
  17.             return _Command.Undo();  
  18.         }  
  19. }  
Transaction class is just a DTO used to pass parameters to the commands. This is not a part of Command Pattern.

  1. public class Transaction  
  2. {  
  3.         public int Amount { getset; }  
  4.   
  5.         public int BalanceAmount { getset; }  
  6. }  
Following is how clients will use the command pattern to invoke commands.

  1. static void Main(string[] args)  
  2. {  
  3.             int bal = 0;  
  4.              
  5.             BaseCommand cmdDeposit = CommandFactory.GetCommand("Deposit");  
  6.   
  7.             Transaction trans1 = new Transaction();  
  8.             trans1.Amount = 1000;  
  9.   
  10.             CommandInvoker invoker1 = new CommandInvoker(cmdDeposit);  
  11.   
  12.             bal = invoker1.ExecuteCommand(trans1);  
  13.   
  14.             Console.Write("Amount deposited. Your balance is: " + bal.ToString());  
  15.   
  16.             //------------------             
  17.   
  18.             BaseCommand cmdWithdraw = CommandFactory.GetCommand("Withdraw");  
  19.   
  20.             trans1.Amount = 400;  
  21.   
  22.             CommandInvoker invoker2 = new CommandInvoker(cmdWithdraw);  
  23.   
  24.             bal = invoker2.ExecuteCommand(trans1);  
  25.   
  26.             Console.Write("Amount withdrawn. Your balance is: " + bal.ToString());  
  27.   
  28.             // -- Undo withdraw  
  29.             bal = invoker2.UndoCommand();  
  30.   
  31.             Console.Write("Withdrawal Undone. Your balance is: " + bal.ToString());  
  32.   
  33.             Console.Read();  
  34.         }  
  35. }  
CommandFactory is just a utility class. This is not a part of Command Pattern.

  1. public static class CommandFactory  
  2. {  
  3.         public static BaseCommand GetCommand(String command)  
  4.         {  
  5.             switch (command)  
  6.             {  
  7.                 case "Deposit":  
  8.                     return new ConcreteCommandDeposit();  
  9.   
  10.                 case "Withdraw":  
  11.                     return new ConcreteCommandWithdraw();  
  12.                       
  13.                 default:  
  14.                     return null;  
  15.             }  
  16.   
  17.         }  
  18. }  

Summary

Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls without the need to know the owner of the method or the method parameters.

Reference:

 
  

Design Pattern : Iterator Pattern Implementation

Iterator pattern allows sequential access of elements with out exposing the inside code. Let’s understand what it means. Let’s say you have a collection of records which you want to browse sequentially and also maintain the current place which recordset is browsed, then the answer is iterator pattern. It’s the most common and unknowingly used pattern. Whenever you use a ‘foreach’ (It allows us to loop through a collection sequentially) loop you are already using iterator pattern to some extent.

Figure: - Iterator business logic

In figure ‘Iterator business logic’ we have the ‘clsIterator’ class which has collection of customer classes. So we have defined an array list inside the ‘clsIterator’ class and a ‘FillObjects’ method which loads the array list with data. The customer collection array list is private and customer data can be looked up by using the index of the array list. So we have public function like ‘getByIndex’ ( which can look up using a particular index) , ‘Prev’ ( Gets the previous customer in the collection , ‘Next’ (Gets the next customer in the collection), ‘getFirst’ ( Gets the first customer in the collection ) and ‘getLast’ ( Gets the last customer in the collection).

So the client is exposed only these functions. These functions take care of accessing the collection sequentially and also it remembers which index is accessed.

Below figures ‘Client Iterator Logic’ shows how the ‘ObjIterator’ object which is created from class ‘clsIterator’ is used to display next, previous, last, first and customer by index.


Figure: - Client Iterator logic

Reference:

Design Pattern : Mediator Pattern Implementation

Many a times in projects communication between components are complex. Due to this the logic between the components becomes very complex. Mediator pattern helps the objects to communicate in a disassociated manner, which leads to minimizing complexity.
Figure: - Mediator sample example

Let’s consider the figure ‘Mediator sample example’ which depicts a true scenario of the need of mediator pattern. It’s a very user-friendly user interface. It has three typical scenarios.
Scenario 1:- When a user writes in the text box it should enable the add and the clear button. In case there is nothing in the text box it should disable the add and the clear button.
Figure: - Scenario 1

Scenario 2:- When the user clicks on the add button the data should get entered in the list box. Once the data is entered in the list box it should clear the text box and disable the add and clear button.
Figure: - Scenario 2

Scenario 3:- If the user click the clear button it should clear the name text box and disable the add and clear button.
Figure: - Scenario 3

Now looking at the above scenarios for the UI we can conclude how complex the interaction will be in between these UI’s. Below figure ‘Complex interactions between components’ depicts the logical complexity.
Figure: - Complex interactions between components

Ok now let me give you a nice picture as shown below ‘Simplifying using mediator’. Rather than components communicating directly with each other if they communicate to centralized component like mediator and then mediator takes care of sending those messages to other components, logic will be neat and clean.
Figure: - Simplifying using mediator
Now let’s look at how the code will look. We will be using C# but you can easily replicate the thought to JAVA or any other language of your choice. Below figure ‘Mediator class’ shows the complete code overview of what the mediator class will look like.

The first thing the mediator class does is takes the references of the classes which have the complex communication. So here we have exposed three overloaded methods by name ‘Register’. ‘Register’ method takes the text box object and the button objects. The interaction scenarios are centralized in ‘ClickAddButton’,’TextChange’ and ‘ClickClearButton’ methods. These methods will take care of the enable and disable of UI components according to scenarios.
Figure: - Mediator class

The client logic is pretty neat and cool now. In the constructor we first register all the components with complex interactions with the mediator. Now for every scenario we just call the mediator methods. In short when there is a text change we can the ‘TextChange’ method of the mediator, when the user clicks add we call the ‘ClickAddButton’ and for clear click we call the ‘ClickClearButton’.
Figure: - Mediator client logic

Reference:
 

C# Iterations: IEnumerator, IEnumerable and Yield

Directly using IEnumerator for iterations

Enumerators are used to read data in the collection. The foreach statement hides the complexity of the enumerators, but you can directly manipulate IEnumerator for customized iterations. Let's do an example:

Code:
List<string> myList = new List<string>();for (int i = 0; i < 10; i++)
{
    myList.Add("Item " + i.ToString());
}
IEnumerator<string> myEnum = myList.GetEnumerator();

myEnum.Reset();           
myEnum.MoveNext();
myEnum.MoveNext();
myEnum.MoveNext();
System.Console.WriteLine(myEnum.Current);
myEnum.MoveNext();
myEnum.MoveNext();
System.Console.WriteLine(myEnum.Current);
myEnum.Reset();
myEnum.MoveNext();
System.Console.WriteLine(myEnum.Current);

Output:
Item 2
Item 4
Item 0

In order to reach the first element, you should run MoveNext method of Enumerator. Initial Position of Enumerator does not point the first element.

Implementing IEnumerable and IEnumerator on your custom objects

IEnumerable interface should be implemented in order to use your custom objects in the form of a collection (series of values or objects). Which means you can use it directly with the foreach statement. IEnumerable interface has a method called GetEnumerator() which returns an object implemented IEnumerator. Let's do an example: PowersOfTwo class implements IEnumerable so any instance of this class can be accessed as a collection.
class PowersOfTwo : IEnumerable<int>
{      
    public IEnumerator<int> GetEnumerator()
    {
        return new PowersOfTwoEnumerator();
    }       
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }       
}
Test:
PowersOfTwo p2 = new PowersOfTwo();foreach (int p in p2)
{
    System.Console.WriteLine(p);
}


Output:

2 4 8 16 32 64 128 256 512 1024


Actually the magic trick lies in the PowersOfTwoEnumerator Class
    class PowersOfTwoEnumerator : IEnumerator<int>
    {
        private int index = 0;
        public int Current
        {
            get { return (int)System.Math.Pow(2, index); }
        }

        object System.Collections.IEnumerator.Current
        {
            get { return Current; }
        }
        public bool MoveNext()
        {
            index++;
            if (index > 10)
                return false;
            else                return true;
        }
        public void Reset()
        {
            index = 0;
        }
        public void Dispose()
        {
        }
    }


Current returns the same element until MoveNext is called. Initial index is zero each MoveNext method incriments the index by 1 up to 10 then it returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false. If the last call to MoveNext returned false, Current is undefined. You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead. IEnumerator inherits IDisposible for performance only.

Using The Yield Keyword

yield keyword is introduced by C# 2.0 in order to implement iteartion easier. On the other hand it has some disadventages. Let's first look at the yield keyword.
public IEnumerable<int> GetPowersofTwo()
{
   for (int i = 1; i < 10; i++)       yield return (int)System.Math.Pow(2, i);   yield break;
}


Yield is not a feature of the .Net runtime. It is just a C# language feature. During compilation Compiler converts yield method and its class to instances of IEnumerable and IEnumerator implemented classes.

Criticism of the keyword "yield"

"yield" has a couple of drawbacks first of all it is designed to simplify implementing iterations. But it can be used to write very ill designed code (like goto). There are many bad examples therefore I am not going to write one here. But using it for other than the intended purpose will make your code hard to follow.

Second problem is that "yield" does not make sense in Object Oriented paradigm just like delegates. I believe as long as languages stick to a single paradigm they become more understandable and structured. When Microsoft introduced C# they decided to use delegates as an event mechanism, instead of interfaces. Delegates are function pointers and have no meaning in OOP. A similar problem exists for yield too, when you look at the above example, the method signature tells you that GetPowersofTwo will return an object implemented IEnumerable. But it is not the case.

Example 2 


In the .NET Framework, there are two interfaces designed to allow you to iterate easily over collections of objects as you would typically do in a for loop. Many classes in the .NET Framework have implemented these interfaces and do their work behind the scenes so you don’t have to worry about how it is done. However, sometimes you want to have the control to do this yourself.
Maybe you have the need to create a custom class that holds a collection of objects, and you want to be able to iterate over them. It’s pretty straightforward to do this in C# or VB.NET. You have to implement two interfaces called IEnumerable and IEnumerator. Below is a trivial example (because it’s already possible to do this with the List class) that illustrates how you would go about implementing these to iterate over a collection of string objects:

using System;
using System.Collections.Generic;
using System.Collections;
 
namespace Demo
{
 public class TestOverride : IEnumerable<string>
 {
                private List<string> _values;
 
                public TestOverride(List<string> values)
                {
                    _values = values;
                }
 
  public IEnumerator<string> GetEnumerator()
  {
      return new TestOverrideEnumerator(_values);
  }
 
  IEnumerator IEnumerable.GetEnumerator()
  {
   return GetEnumerator();
  }
 
  protected class TestOverrideEnumerator : IEnumerator<string>
  {
   private List<string> _values;
   private int _currentIndex;
 
   public TestOverrideEnumerator(List<string> values)
   {
    _values = new List<string>(values); 
    Reset();
   }
 
   public string Current
   {
    get { return _values[_currentIndex]; }
   }
 
   public void Dispose() {}
 
   object IEnumerator.Current
   {
    get { return Current; }
   }
 
   public bool MoveNext()
   {
    _currentIndex++;
    return _currentIndex < _values.Count;
   }
 
   public void Reset()
   {
    _currentIndex = -1;
   }
  }
 }
}
I’m sure there’s a better way to do this, but it should help you get started. Note that you have to implement both classes and that the most work is done in the class that implements IEnumerator. Also note that you can use generics (in this case force it to iterate only over string objects).
You would invoke this functionality this way:

List<string> collection = new List<string>();
collection.Add("abc");
collection.Add("def");
collection.Add("ghi");
 
TestOverride collectionWrapper = new TestOverride(collection);
 
foreach (string x in collectionWrapper)
    Console.Out.WriteLine(x);
 
 
 
 

C# : Yield Statement

Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration. It takes one of the following forms:
yield return <expression>;
yield break;
 
You will want to use the yield keyword in methods that return the
type IEnumerable (without any angle brackets), or the type IEnumerable<Type>
with a type parameter in the angle brackets. You need to reference the System.Collections
namespace for the first version, and the System.Collections.Generic namespace for
the second. 

Example1:
In the following example, the yield statement is used inside an iterator block, which is the method Power(int number, int power). When the Power method is invoked, it returns an enumerable object that contains the powers of a number. Notice that the return type of the Power method is IEnumerable, an iterator interface type.

// yield-example.cs
using System;
using System.Collections;
public class List
{
    public static IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
    }

    static void Main()
    {
        // Display powers of 2 up to the exponent 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }
}

Output

 
2 4 8 16 32 64 128 256 
 
 
Example 2: 

using System;
using System.Collections.Generic;
 
    class ExampleYieldReturn
    {
        static void Main(string[] args)
        {
            //with every call it goes to where it left till it encounters yield return
            foreach(int n in GetNumbers())
            {
                Console.WriteLine(n);
            }
 
            Console.ReadLine();
        }
 
    public static IEnumerable<int> GetNumbers()
        {
            Console.WriteLine("Print number 52");
            yield return 52; // will go back to the caller ie foreach
 
            Console.WriteLine("Print number 63");
            yield return 63;// again will go back to the caller ie foreach
 
            Console.WriteLine("Print number 72");
            yield return 72;// again will go back to the caller ie foreach
 
        }
 
    }
 
Output:
Print number 52
52
Print number 63
63
Print number 72
72
Example 3:
 
How to use C# yield to easily return an IEnumerable collection
Using "yield return" instead of "return", you can create IEnumerable collection which you can easily consume in foreach loops and query with LINQ. Notice also that you can just write the method that you want and Visual Studio will allow you to create a stub for it, very convenient.
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestYield
{
    class Program
    {
        static void Main(string[] args)
        {
            //use with foreach
            Console.WriteLine("All ASCII numbers:");
            foreach (int asciiNumber in GetAsciiNumberCollection("This is a test."))
            {
                Console.WriteLine(asciiNumber);
            }

            //use with linq
            Console.WriteLine("Low ASCII numbers:");
            var lowNumbers = from n in GetAsciiNumberCollection("This is a test.")
                             where n <= 90
                             select n;
            foreach (int asciiNumber in lowNumbers)
            {
                Console.WriteLine(asciiNumber);
            }

            Console.ReadLine();
        }

        private static IEnumerable<int> GetAsciiNumberCollection(string line)
        {
            foreach (char letter in line)
            {
                yield return (int)letter;
            }
        }
    }
}