Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, 16 December 2014

"Private" member access within same class

Sometime we are so busy "doing stufff" and miss the most basic concepts.

See the following code (LinqPad):


The key factor to consider here whether the code is going to compile. Actually it compiles and executes without any exceptions.

If you look closely you will see "friend.i.Dump()" and "friend.j.Dump()". This might be a cause for concern. This is because "i" and "j" are private members and how come we can call "f.i" in the "Add" method.

The "private" modifier indicates that the members can only be accessed within the same class. So in this particular case we are "inside" the "Friend" class and members are visible. Reference is here.

In order to prevent this confusion, simply use a property. That is simple and universally understood.

Monday, 12 May 2014

Notes around .NET threading, use of timers etc

I was listening to Jeffrey Richter and he mentioned the how widespread the incorrect use of .NET threads. There is no point reinventing the wheel, simply have a look at the following code. It looks very harmless, however it is a course for real concern.


The comments in the code speak for itself. However is this "better" than using "Thread.Sleep" to pause a thread... :-)

Wednesday, 10 July 2013

Curse of the Base class

Please do not get me wrong, Inheritance has its place.

In this post, I will share a very badly designed base class implementation. The goal is not to criticise someones work, but to learn from it.

Some code

The Platform (developed by a 3ed party) we use had a base-class implementation that was similar to the following.

The class itself looks innocent but it has massive problems. The following is the example provided in the documentation.

So how can we actually unit test this code. Nightmare!

Refactor (ugly)


We need to organise the class so that is it suitable for unit testing.

The following is my first attempt. (Remarks: I am using bastard injection in this example.)

We have removed the call to the base class "Add" method in the derived class "Add". The most odd looking code is in the public constructor. It is calling the internal constructor with "IDatabase" and null. If you remember the constructor resolution order, you might remember that the public constructor is resolved last (in the above example). This means that the "_addAction" delegate is initialised twice. Once with null then by the actual value from the public constructor.


Unit test

Sorry, ideally you should be writing a test first. (TDD!).

The unit test should focus on the code we wrote, not what is provided by the Platform.

Its all here.

Sunday, 16 June 2013

The God object (discovery) [1]

In Software Engineering the God object this refers to an object that every other object depends on. I am sure simple search on the internet will yield dozens of articles describing the pros-n-cons of using a God object.

Me and my wife welcomed our son few weeks ago and I was immensely busy. It is only today that I managed to find few hours to myself to write this note. When it comes to baby stuff, I think whatever the literature that is available in the market is only half the story (or may be less). Having a child changes everything. This ever-hungry machine will forever change your life and mostly in a good way. Yes, you will loose few hours of sleep here and there but I think its absolutely worth it. The joy and happiness that this new member brings to your small family is priceless. Enough talk.... :-)

The God object is like a baby. We know its there, but for an application point of view its a big black box. The God object can do everything, (e,g write to database, file system, resolve dependencies etc). For a development team that is mature, understanding what the God object is not that difficult. However for a new member its similar to becoming a father/mother for the first time. You just know its there, but just do not know how to use it!

So what do I know about the Baby (God) object. The only thing that I knew at the beginning was it derived from a very generic class Person. Thanks to to modern wonders of science and technology we found out the gender of the baby. Therefore we knew its a Person and had a property called Gender which was set to to Male. So my abstract world looked like this.



After the baby was born I soon realise that this God object has a very simple and effective behavior. Crying. I have to say is very effective and the best way to model this behavior was to implement ICanCry interface. Crying can sometimes be a Big thing! especially for a new born. My object model was evolving.  



My son is very special to me, therefore I did not hesitate to make a brand new instance of this Person. We cannot create an instance of a Abstract class, however we can derive from it. I called this specialisation TheSpecialOne.

You might wonder why I decided Abstract the "Cry()" method as above. The reason is quite simple. Each baby cries differently. Some can be very loud but others are not. Therefore I decided my son can decide how best to cry :-). 

This does not look right, don't you agree? Well, every person should have a gender. We need to ensure that this is a required property. The best way to make sure that the Gender is populated is to have the Person class to contain a constructor that takes in the gender as a parameter.

We were starting to forget the most important piece of the puzzle. The Name. There is no doubt that a person should have a name, therefore I introduced the new Name property to the Person class.



Few hours after the baby was born he was ready to feed. As this is a fundamental behavior of a person, I thought of introducing this behavior to the Person class for the moment.


It did not take even few more hours to realise another fundamental behaviors. These were "poo" and "sleep". So I modeled this in to my glorified Person class. 



One thing I did do was to implement "Poo" in the base class itself. Whatever we take has to come out at some point. Therefore I did not really see the point of having a specialisation of "Poo" in my TheSpecialOne class.

So far my son is feeding, sleeping, crying and can poo. (Code is here.)

Friday, 12 April 2013

("quirky") Entity Framework with DatabaseGeneratedOption.Identity

I am pretty impressed with Entity Framework 5 so far. Especially Entity Framework Code First is a massive time saver!

Caution
I recently needed to share a reference to a row in a table with an external system. Simplest solution is to share the primary key which most of the time is auto incremental unique value. From the outset this does not look too bad. However, sharing primary keys can be a massive security flow. If a someone gets hold of the primary key, they can "guess" what the next key might be.

Setup
Entity Framework kindly provide us a standard pattern to setup a primary key for an entity. See the following model class.


The "Id" is set to be the primary key, with the seed and increment set to 1. See the following illustration.



It is never a good idea to share technical keys outside the application boundary. The way around is to have random key that is uniquely identifies the row. We can achieve this by introducing a new "Reference" column with the type "GUID". The modified model class looks like the following.


Problem
There two ways to populate the GUID. The simplest approach is to create a new GUID (GUID.NewGuid()) just before saving the entity.  This is proven to work and reliable.

Alternatively we can get the database to do the work and generate a new GUID. In order to force the database to create the GUID automatically, we need to "inform" Entity Framework our intention. The first step is the update the model class to the following. (BTW you need to reference System.ComponentModel.DataAnnotations.Schema namespace). I am using data annotation, but the same behavior can be achieved by the Entity Framework fluent API.


I find the syntax pretty strange. We are basically saying that "Reference" is the "identity" of the entity. Does this mean primary key is no longer the "identity"? (we'll find out soon).

If you regenerate the database (using Entity Framework Code First) what you see may surprise you. By the outset the table looks pretty good. (see the illustration).


As expected the "Id" is the primary key and the "Reference" is an uniqueidentifier field.The biggest surprise is the seed and the increment for the primary key. (see below.)


The seed and the increment is not set and worse "Id" column is no longer the identity. This is strange. 

If we dig a just a bit deeper, we see how SQL Server generate the uniqueidentifier automatically (see below).


The "DefaultValue" is set to "NewId()" which is how SQL Server generate a GUID. When a new row is added, the "NewId()" function is invoked and it populates the "Reference" column.

Solution
We yet fix the problem. Our desire is to have an incremental primary key and a random "Reference". In order to achieve this, we need to update the model to the following. 


The key point here is that we have added "DatabaseGeneratedOption.Identity" to the "Id". This adds the seed and increment to "Id". So when we add a new entity database, automatically generate a random "GUID". The GUID is safe and can be shared externally.

Sunday, 24 March 2013

Reading Blobs from SQL Server in chunks

There are many reasons why we want to store blobs in SQL Server, instead of a path to a file. Security  might be a very good reason.

We can use the varbinary type in SQL Server to store blob data. 

So, lets say that we managed to get some blob data to SQL Server. We can simply use ADO.NET, Entity Framework to read this data. This task is straight forward. Now, consider the scenario where there is a large blob, and we want to read it in chucks. We might do this in order to optimise the application performance (streaming), network traffic. We do not want our applications to "hang", while blobs are being read from SQL Server!

I have created a very simple table, and the schema looks like below: 



Lets get some binary data to our table:


Ensure to replace the path to a file in your system. 

I will be using Visual Studio Express 2012. Instead of just showing the code, I would like to highlight the most important points. 

The first stage is to make a connection to the database. For this, we can simply use the SqlConnection class. Thereafter we will use SqlDataReader class to read the data. The following is the first part of the class.


Don't worry too much about this, just keep an eye on the SqlConnection and SqlDataReader. In the constructor, I have created an instance of SqlConnection with a connection string. Again, you will need to set your own connection string. 

The next point is the "CommandString". This is the SQL I will be using to read data from our table. The keyword that stands out from this string is "DATALENGTH". We use DATALENGTH  to find out the size (length) of the byte stream stored in the "Payload" column.

The DATALENGTH function returns the number of bytes in the "Payload". We will be reading 1MB at time and I have created the "ChunkSizeBytes" variable to store the maximum size of the chunk. 

We can now open the connection the database. 

In the above method, I have used SqlCommand class and has initialised it with the "CommandString" and the connection. Thereafter we can execute the command with the "SequentialAccess" command behavior. This is the most important piece of the puzzle. By using this behavior we are essentially configuring our connection not to read the entire blob, but read it as a stream. The next behavior is "CloseConnection", which closes the connection when the reader finished reading. 

Next step is to read the data.


The above method reads the "Payload" data in 1MB chunks. We use the "GetBytes" method to read the chunk. Yes, there are many optimisations that you can do to this method. The first is not to "re-initialise" the "bytes" variable, but to reuse it. 
What is basically happening here is that, the "callback" delegate is invoked for each chunk. 

 The Console application looks like below:


Nothing major, I simply write the bytes to a file. This is what I got when I execute the application.


You can see that the delegate was called 5 times and we did not receive the full 1MB in the last attempt. 


We can see that the file is only 4.6MB, and maps directly to the results we saw in the console application. 

My PDF works!


Enjoy! (BTW - code is here)

Monday, 11 February 2013

"Simple" Service Locator

The Service Locator pattern has been subjected to many arguments and surely it will continue for many more years. As usual the best source to learn about the Service Locator pattern is from Martin Fowler.


 Design patterns 


Design patterns, when used correctly can help to "craft" the software. However design patterns can easily make the code hard to understand too. So I guess there should always be a balance. My objective of this post is not to argue that Service Locator is an anti-pattern or not. My goal is just to write few lines of code and see how all fits together. I thought I will write a "form" of service locator that anyone can understand. 

"Simple" Service Locator 


The interface of the "simple" Service Locator looks like below:

I created a simple Console application that uses this Service Locator. The usage looks like below:



Limitations 

A type must always implement an Interface.
A type implementing multiple interfaces must be registered separately.
Only an interface can be registered against a type. ... etc etc, Many more.

If you interested in the code you can download it from GitHub.

Wednesday, 18 July 2012

Back to basics (IDisposable)

In simple terms Disposable pattern provides a method to de-allocate resource in a deterministic fashion.

The .NET Framework provides the  "IDisposable" interface which we should use to implement the disposable pattern. The interface is very simple (see below).

        public interface IDisposable
        {
            void Dispose();
        }


The "expensive" resources are considered to be calls to files, databases, streams. We should consider implementing IDisposable pattern and gracefully release resources where necessary. So, how do we go about implementing the IDisposable pattern. Consider the following code snippet.

    internal class ExpensiveResource : IDisposable
    {
        private bool _disposed = false;

        public void DoExpensiveWork()
        {
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                ReleaseExpensiveResources();
                _disposed = true;
            }
        }

        private void ReleaseExpensiveResources()
        {

        }
    }

 To start, we have implemented the "IDisposable" interface for the type "ExpensiveResource". We have a overloaded  "Dispose" method. We use the overloaded method to add our custom code (i.e. code to release resources). 

Most importantly, the "Dispose" method can be called multiple times.Therefore we need to add safe guards in place. This is where "_disposed" field comes into play.

Since we are taking the ownership of disposing the object, there is no need for the Garbage Collector (GC) to call the "Finalize" method to dispose the object. Therefore we can suppress the call to Finalize. This is carried out by calling the "GC.SuppressFinalize(this))".

The C# "using" keyword can be used to elegantly dispose a disposable object. The consumer can write the following.

    internal class MyTestClass
    {
        public void DoStuff()
        {
            using (var expensiveWork = new ExpensiveResource())
            {
                // Do work
            }  - (1)
        }
    }

By the time the execution reach (1) the dispose defined in the type is called and object is disposed. 

.NET Tasks and IDisposable

.NET Framework "Task" by design implements the "IDisposable" interface, therefore an disposable object. But if we have to keep calling dispose at the end of each Task, then the source code will most surely become unreadable.

Read the following post from Stephen Toub - MSFT for more on disposing Tasks.

[The recommendation is not to dispose a Task unless you explicitly cause a Task to allocate a  IAsyncResult.AsyncWaitHandle.]

Sunday, 10 June 2012

ASP.NET MVC 3 - SportsStore [using MVC 4]

I started reading the ASP.NET MVC3 book few weeks ago. The part 1 of the book builds a very nice e-commerce application called "Sports Store".

I have to admit that I read the ASP.NET MVC 2 by Steven Sanderson while ago. It was a one of the greatest reads! (I mean from cover to cover). Although Steven was involved with the ASP.NET MVC 3 book, I felt that it was bit rushed. But I really enjoyed it!

Since, MVC 4 and Visual Studio 2011 (beta)  are already in preview stage, I thought the best way to learn is to code "Sports Store" application using Visual Studio 2011 Beta and MVC 4.

I uploaded the project to codeplex too..
Sports Store using MVC 4 in CodePlex

See some of the screen captures.. (sorry about the images)

All Products

Products by category

Editing

Tuesday, 22 May 2012

Visiting the visitor pattern

A colleague of mine showed me the following result.


----------------------------------------------------------------
Current Drawing
----------------------------------------------------------------
Rectangle (10,10) width=30 height=40
Square (15,30) size=35
Ellipse (100,150) diameterH = 300 diameterV = 200
Circle (1,1) size=300
Textbox (5,5) width=200 height=100 Text="sample text"


He asked me whether I can write a simple console application to achieve the above result. Simple task you might say.

Well.. it is pretty obvious that we need to start off with an abstract "Shape" class. But what about the logic to "draw" the shape on the canvas. What we need is an interface like "ICanDraw", which contains the "draw" method. Now, the Shapes can be drawn, therefore the Shape should implement the "ICanDraw" interface. But hang on, each Shape should present itself to the canvas. The canvas should then decide how to "draw" the shape on the canvas.

The most interesting piece here is the text box.  A text box is not strictly a shape, but a "Rectangle" with a additional text property. We can say that a text box is composed of a Rectangle. Internally the text box will use the Rectangle to represent itself.

See the following UML.



My "ICanDraw" interface looks like below.


    /// <summary>
    /// This interface indicates that the shape can be drawn.
    /// </summary>
    public interface ICanDraw
    {
        void Draw(ICanvas canvas);
    }


The abstract "Shape" class looks like below.


    /// <summary>
    /// This is the base class for a shape.
    /// </summary>
    public abstract class Shape : ICanDraw
    {
        public int X { get; private set; }
 
        public int Y { get; private set; }
 
        protected Shape(int x, int y)
        {
            X = x;
            Y = y;
        }
 
        public abstract void Draw(ICanvas canvas);
    }


Keep a close eye on the abstract "Draw" method. Also notice that the "X" and "Y" are "readonly" properties. This plays nicely to the immutability of objects

The "Circle" class looks like below:


    /// <summary>
    /// This is the concrete implementation of a circle.
    /// </summary>
    public class Circle : Shape
    {
        public int Size { get; private set; }
 
        public Circle(int x, int y, int size)
            : base(x, y)
        {
            Size = size;
        }
 
        public override void Draw(ICanvas canvas)
        {
            canvas.Draw(this);
        }
    }


The code for the text box looks like below.


    /// <summary>
    /// This is the concrete implementation of a text box.
    /// </summary>
    public class Textbox : ICanDraw 
    {
        public Rectangle Rectangle { get; private set; }
 
        public string Content { get; private set; }
 
        public Textbox(int x, int y, int width, int height, string content)
        {
            Rectangle = new Rectangle(x, y, width, height);
            Content = content;
        }
 
        public void Draw(ICanvas canvas)
        {
            canvas.Draw(this);
        }
    }


Ok, we have all the concrete classes and a special text box.

Next piece of the puzzle is the "ICanvas". Since we are just writing the content to the console, this will be a special console canvas. The canvas is aware of the shapes and will decide how to draw them. The responsibility to draw a shape is now with the canvas.

The following is the special implementation of "ICanvas" for the console.


/// <summary>
    /// This is the "canvas" representing the console.
    /// </summary>
    public class ConsoleCanvas : ICanvas 
    {
        public void Draw(Circle item)
        {
            Console.WriteLine("Circle({0},{1}) Size={2}", item.X, item.Y, item.Size);
        }
 
        public void Draw(Rectangle item)
        {
            Console.WriteLine("Rectangle({0},{1}) Width={2}, Height={3}", item.X, item.Y, item.Width, item.Height);
        }
 
        public void Draw(Square item)
        {
            Console.WriteLine("Square({0},{1}) Size={2}", item.X, item.Y, item.Size);
        }
 
        public void Draw(Ellipse item)
        {
            Console.WriteLine("Ellipse({0},{1}) DiameterH={2}, Diameter={3}", item.X, item.Y, item.DiameterH, item.DiameterV);
        }
 
        public void Draw(Textbox item)
        {
            Console.WriteLine("TextBox({0},{1}) Width={2}, Height={3}, Text={4}", item.Rectangle.X, item.Rectangle.Y, item.Rectangle.Width, item.Rectangle.Height, item.Content);
        }
    }


As you can see the canvas is aware of the shapes and it decides how to draw them. The canvas will determine this by the runtime type of the object.

Can you see a pattern here? This is in fact the "Visitor" pattern. The purpose of the visitor pattern is to choose a functionality depending on the run-time type of an object. The pattern is also used to introduce additional functionality to an object.

So how do we "draw" these shapes. See below.


        private static void Load()
        {
            var items = new List<ICanDraw>()
                            {
                                new Rectangle(10, 10, 30, 40),
                                new Square(15, 30, 35),
                                new Ellipse(100, 150, 300, 200),
                                new Circle(1, 1, 300),
                                new Textbox(5, 5, 200, 100, "Sample Text")
                            };
 
            items.ForEach(item => item.Draw(new ConsoleCanvas()));
        }

The special "ConsoleCanvas" visits each shape and "draws" it on the console.

In terms of SOLID principals, the "Shape" class is open for extensions and closed for modifications . Yes, the Open/Close principal.

But can the same functionality be achieved through another pattern?

Saturday, 5 May 2012

State and Strategy patterns

The State and Strategy patterns are very similar to each other but their use is somewhat different.

The state pattern is a way of encapsulating the behaviour of each state an object goes through. The state pattern fits nicely to model the operation of an ATM machine.

The key difference is that the state pattern is used to identify "states" which an object goes through. Where as the strategy pattern encapsulates a behaviour of the object. The state classes can be aware of the other states. This raise the question of coupling. For a system that is dynamically changing, then having states "knowing" other states might be acceptable.

The strategy on the other hand is an isolated functional unit and there is no interaction between the strategies. The context can choose which strategy to use where as the state is changed by changes to the internal state of the object. The most obvious way to use the strategy pattern is with the factory method.

Sunday, 15 April 2012

Visitor Pattern : Revisited

Some developers find design patterns an "Advance" topic. But the reality is that we use design pattern every day and mostly without even knowing.

I find design patterns as an essential element in everyday development. I agree that reading the "Design Patterns" by the Gang of Four (GOF) can be challenging. But trust me, its worth the effort. Although I have not read this book cover to cover, it is an essential reference that you should have access to.

The intent of Visitor pattern according to GOF is "Represent an operation to be performed on elements of an object structure. Visitor lets you to define a new operation without changing the classes of the elements on which it operates.". I think for a developer, the second sentence is the most important piece "without changing the classes".

Consider an example where two tax rate applied to people based on their earnings. The idea here is to  create a "Visitor" to calculate the tax.

[Lets have a quick look at the UML. - Created using Creately]

















Lets start with the "Person" class. This is an abstract class.


    /// <summary>
    /// This is the base class for people.
    /// </summary>
    public abstract class Person
    {
        public string Name { get; private set; }
 
        protected Person(string name)
        {
            Name = name;
        }
 
        /// <summary>
        /// Accept a visitor so that new functionality can be added to the <see cref="Person"/>.
        /// </summary>
        public abstract void Accept(IVisitor visitor);
    }


The above immutable class has a method called "Accept". This is where we "inject" the visitor. The "Person" class is ready to entertain a "Visitor".

The next step is to create the two types of people. In this example they are high and low earners.


    /// <summary>
    /// This is a concrete class of a <see cref="Person"/>.
    /// </summary>
    public class HighEarningPerson : Person
    {
        public decimal Salary { get; private set; }
 
        public decimal Rate { get; private set; }
 
        public HighEarningPerson(string name, decimal salary, decimal rate)
            : base(name)
        {
            Salary = salary;
            Rate = rate;
        }
 
        /// <summary>
        /// The Visitor to this object works on the <see cref="HighEarningPerson"/> instance.
        /// </summary>
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }


This is followed by the low earning person.


/// <summary>
    /// This is a concrete class of a <see cref="Person"/>.
    /// </summary>
    public class LowEarningPerson : Person
    {
        public decimal Salary { get; private set; }
 
        public decimal Rate { get; private set; }
 
        public LowEarningPerson(string name, decimal salary, decimal rate)
            : base(name)
        {
            Salary = salary;
            Rate = rate;
        }
 
        /// <summary>
        /// The Visitor works on the instance of <see cref="LowEarningPerson"/>.
        /// </summary>
        /// <param name="visitor"></param>
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }


Both classes looks similar, but take a closer look at the "Accept" method. The "Accept" method receives the "Visitor" and calls the "Visit" method passing in the current object. The "Visitor" is now aware of the type of person it is dealing with.

The following is the interface of the "IVisitor".


    /// <summary>
    /// This is the interface of the Visitor that 
    /// works on the concrete types of people. 
    /// </summary>
    public interface IVisitor
    {
        void Visit(HighEarningPerson highEarningPerson);
 
        void Visit(LowEarningPerson lowEarningPerson);
    }


The "IVisitor" works with the concrete "Person" types. So in this case "HighEarningPerson" and "LowEarningPerson". You can see that "IVisitor" is using the method overloading.

Lets look at the implementation of the "IVisitor".


    /// <summary>
    /// This is the Visitor that calculates the tax for each person.
    /// </summary>
    public class TaxVisitor : IVisitor
    {
        private readonly ITaxCalculatorFactory _taxCalculatorFactory;
 
        public TaxVisitor(ITaxCalculatorFactory taxCalculatorFactory)
        {
            _taxCalculatorFactory = taxCalculatorFactory;
        }
 
        public void Visit(HighEarningPerson highEarningPerson)
        {
            var taxCalculator = _taxCalculatorFactory.Create(TaxType.High);
            var tax = taxCalculator.Calculate(highEarningPerson.Salary, highEarningPerson.Rate);
 
            Console.WriteLine("The tax for '{0} - HIGH' is £{1:00}", highEarningPerson.Name, tax);
        }
 
        public void Visit(LowEarningPerson lowEarningPerson)
        {
            var taxCalculator = _taxCalculatorFactory.Create(TaxType.Low);
            var tax = taxCalculator.Calculate(lowEarningPerson.Salary, lowEarningPerson.Rate);
 
            Console.WriteLine("The tax for '{0} - LOW' is £{1:00}", lowEarningPerson.Name, tax);
        }
    }


Do not pay too much attention to the "ITaxCalculatorFactory" that is used here. The reason for using the "ITaxCalculatorFactory" is to keep the creation of the objects out from business processes. Always keep in a note of the Inversion of Control (IoC).

The "TaxVisitor" calculates the tax rate of each person and displays the result.

Lets see how all of this fits in..

I have created a "Console" application. See the following class.


public class VisitorPattern : ITest
    {
        public void Execute()
        {
            Console.WriteLine("**** VISITOR Pattern *****");
            var lowTaxRate = 0.023M;
            var highTaxRate = 0.04M;
 
            var people = new List<Person>()
                             {
                                 new LowEarningPerson("Bob", 23000, lowTaxRate),
                                 new HighEarningPerson("Alice", 45000, highTaxRate),
                                 new LowEarningPerson("Peter", 13000, lowTaxRate),
                                 new HighEarningPerson("Pan", 100000, highTaxRate)
                             };
 
            var taxCalculatorFactory = new TaxCalculatorFactory();
            var taxVisitor = new TaxVisitor(taxCalculatorFactory);
 
            people.ForEach(person => person.Accept(taxVisitor));
        }
    }


We have a collection of "Person" objects. Each has its own type (Low and High earnings). The "TaxVisitor" visits each object and calculates the tax. The output looks like below.


We can clearly see that correct calculate method in the "TaxVisitor" is been called based on the type of the object.

The Visitor pattern is uses the "double-dispatch" to resolve a method call. Double-dispatch simply means the ability to choose the correct method at run-time. So in the above case, although we iterate over a collection of "Person" objects, the run-time type has been used to pick the correct method in the visitor.

Hope you will find this note useful.