A Simple Merge Sort Implementation [C#]

Merge Sort
MergeSort is a “divide and conquer” algorithm that splits an array into two halves (sub arrays) and recursively sorts each sub array before merging them back into one giant, sorted array.
In this blog, I will provide a simple implementation of MergeSort with comments on every significant line of code for beginners to quickly grasp the algorithm.


if array.length <= 1 then
return array 
left = new array
right = new array 
mid = left+ right/2
merge(left, right) 
  1. class MergeSort
  2.     {
  3.         public static int[] mergeSort(int[] array)
  4.         {
  5.             int[] left;
  6.             int[] right;
  7.             int[] result = new int[array.Length];
  8.             //As this is a recursive algorithm, we need to have a base case to 
  9.             //avoid an infinite recursion and therfore a stackoverflow
  10.             if (array.Length <= 1)
  11.                 return array;
  12.             // The exact midpoint of our array
  13.             int midPoint = array.Length / 2;
  14.             //Will represent our ‘left’ array
  15.             left = new int[midPoint];
  16.             //if array has an even number of elements, the left and right array will have the same number of 
  17.             //elements
  18.             if (array.Length % 2 == 0)
  19.                 right = new int[midPoint];
  20.             //if array has an odd number of elements, the right array will have one more element than left
  21.             else
  22.                 right = new int[midPoint + 1];
  23.             //populate left array
  24.             for (int i = 0; i < midPoint; i++)
  25.                 left[i] = array[i];
  26.             //populate right array        
  27.             int x = 0;
  28.             //We start our index from the midpoint, as we have already populated the left array from 0 to 
  29.             midpont
  30.             for (int i = midPoint; i < array.Length; i++)
  31.             {
  32.                 right[x] = array[i];
  33.                 x++;
  34.             }
  35.             //Recursively sort the left array
  36.             left = mergeSort(left);
  37.             //Recursively sort the right array
  38.             right = mergeSort(right);
  39.             //Merge our two sorted arrays
  40.             result = merge(left, right);
  41.             return result;
  42.         }
  43.         //This method will be responsible for combining our two sorted arrays into one giant array
  44.         public static int[] merge(int[] left, int[] right)
  45.         {
  46.             int resultLength = right.Length + left.Length;
  47.             int[] result = new int[resultLength];
  48.             //
  49.             int indexLeft = 0, indexRight = 0, indexResult = 0;
  50.             //while either array still has an element
  51.             while (indexLeft < left.Length || indexRight < right.Length)
  52.             {
  53.                 //if both arrays have elements
  54.                 if (indexLeft < left.Length && indexRight < right.Length)
  55.                 {
  56.                     //If item on left array is less than item on right array, add that item to the result array
  57.                     if (left[indexLeft] <= right[indexRight])
  58.                     {
  59.                         result[indexResult] = left[indexLeft];
  60.                         indexLeft++;
  61.                         indexResult++;
  62.                     }
  63.                     // else the item in the right array wll be added to the results array
  64.                     else
  65.                     {
  66.                         result[indexResult] = right[indexRight];
  67.                         indexRight++;
  68.                         indexResult++;
  69.                     }
  70.                 }
  71.                 //if only the left array still has elements, add all its items to the results array
  72.                 else if (indexLeft < left.Length)
  73.                 {
  74.                     result[indexResult] = left[indexLeft];
  75.                     indexLeft++;
  76.                     indexResult++;
  77.                 }
  78.                 //if only the right array still has elements, add all its items to the results array
  79.                 else if (indexRight < right.Length)
  80.                 {
  81.                     result[indexResult] = right[indexRight];
  82.                     indexRight++;
  83.                     indexResult++;
  84.                 }
  85.             }
  86.             return result;
  87.         }
  88.     }
You can now go ahead and call your MergeSort(array) method from Main to see the results.

Sending, Receiving And Deleting Emails In C#

Sending, Receiving And Deleting Emails In C#

Email, abbreviated for electronic mail, is a method of exchanging messages between people using electronics. It’s now being widely used in our daily communication. In this blog, I will show how to send, receive and delete email messages programmatically using C# and a .net Email component.


Before start, we need to add reference to the project by use the following PowerShell command in Visual Studio Nuget Package Manager Console.

  1. PM> Install-Package Spire.Email

Using the code

Sending emails

MailMessage class is used to create email messages. To send email messages, we’ll need to use the SmtpClient class. For the following demo, I’m sending an email with plain text body, you can also create an email with html body by using the BodyHtml property of MailMessage object, instead of BodyText property.

  1. MailAddress addressFrom = “LeonDavisLD@outlook.com”;
  2. MailAddress addressTo = “Shawn_Smithhh@outlook.com”;
  3. MailMessage message = new MailMessage(addressFrom, addressTo);
  4. message.Subject = “Invitation”;
  5. message.BodyText = “Hi Shawn,\r\n” + “This Saturday is my birthday and my parents will hold a simple celebrating party for me. I am glad to invite you to come to the party. Blair, Emma and Roan will also be invited. I am sure we will have a good time. We will have dinner at 18:30 so that you are wished to come at 18:15. My mother is a good cook and you will enjoy the dishes. After the dinner, we will play some small games and then eat the cake. My parents and I sincerely expect you to come and hope to see you then.\r\n “ + “Sincerely Leon “;
  6. SmtpClient smtp = new SmtpClient();
  7. smtp.Host = “smtp.outlook.com”;
  8. smtp.ConnectionProtocols = ConnectionProtocols.Ssl;
  9. smtp.Username = addressFrom.Address;
  10. smtp.Password = “password”;
  11. smtp.Port = 587;
  12. smtp.SendOne(message);
  13. Console.WriteLine(“From : “ + message.From.ToString());
  14. Console.WriteLine(“To : “ + message.To.ToString());
  15. Console.WriteLine(“Subject: “ + message.Subject);
  16. Console.WriteLine(“——————- BODY —————–“);
  17. Console.WriteLine(message.BodyText);
  18. Console.WriteLine(“——————- END ——————“);
  19. Console.WriteLine(“Message Sent.”);
Sending, Receiving And Deleting Emails In C#
Sending, Receiving And Deleting Emails In C#

Receiving and saving emails

Pop3Client and ImapClient is used for receiving email messages. Let’s see how we can retrieve an email message from pop and imap server, and then save it to disk. When saving the email messages, we can choose the message format such as eml, emlx, mhtml and msg from the MailMessageFormat enumeration.

Using Pop3Client

  1. //Create a POP3 client
  2. Pop3Client pop = new Pop3Client();
  3. //Set host, username, password etc. for the client
  4. pop.Host = “outlook.office365.com”;
  5. pop.Username = “LeonDavisLD@outlook.com”;
  6. pop.Password = “password”;
  7. pop.Port = 995;
  8. pop.EnableSsl = true;
  9. //Connect the server
  10. pop.Connect();
  11. //Get the first message by its sequence number
  12. MailMessage message = pop.GetMessage(1);
  13. //Parse the message
  14. Console.WriteLine(“—————— HEADERS —————“);
  15. Console.WriteLine(“From : “ + message.From.ToString());
  16. Console.WriteLine(“To : “ + message.To.ToString());
  17. Console.WriteLine(“Date : “ + message.Date.ToString(CultureInfo.InvariantCulture));
  18. Console.WriteLine(“Subject: “ + message.Subject);
  19. Console.WriteLine(“——————- BODY —————–“);
  20. Console.WriteLine(message.BodyText);
  21. Console.WriteLine(“——————- END ——————“);
  22. //Save the message to disk using its subject as file name
  23. message.Save(message.Subject + “.eml”, MailMessageFormat.Eml);
  24. Console.WriteLine(“Message Saved.”);

Using ImapClient

  1. //Create an IMAP client
  2. ImapClient imap = new ImapClient();
  3. // Set host, username, password etc. for the client
  4. imap.Host = “outlook.office365.com”;
  5. imap.Port = 143;
  6. imap.Username = “LeonDavisLD@outlook.com”;
  7. imap.Password = “password”;
  8. imap.ConnectionProtocols = ConnectionProtocols.Ssl;
  9. //Connect the server
  10. imap.Connect();
  11. //Select Inbox folder
  12. imap.Select(“Inbox”);
  13. //Get the first message by its sequence number
  14. MailMessage message = imap.GetFullMessage(1);
  15. //Parse the message
  16. Console.WriteLine(“—————— HEADERS —————“);
  17. Console.WriteLine(“From : “ + message.From.ToString());
  18. Console.WriteLine(“To : “ + message.To.ToString());
  19. Console.WriteLine(“Date : “ + message.Date.ToString(CultureInfo.InvariantCulture));
  20. Console.WriteLine(“Subject: “ + message.Subject);
  21. Console.WriteLine(“——————- BODY —————–“);
  22. Console.WriteLine(message.BodyText);
  23. Console.WriteLine(“——————- END ——————“);
  24. //Save the message to disk using its subject as file name
  25. message.Save(message.Subject + “.eml”, MailMessageFormat.Eml);
  26. Console.WriteLine(“Message Saved.”);
Sending, Receiving And Deleting Emails In C#
Sending, Receiving And Deleting Emails In C#

Deleting emails

All email messages can be deleted using the DeleteAllMessages() method of Pop3Client class. We can also delete an specific email message with the DeleteMessage() method.

  1. //Create a POP3 client
  2. Pop3Client pop3 = new Pop3Client();
  3. //Set host, authentication, port and connection protocol
  4. pop3.Host = “outlook.office365.com”;
  5. pop3.Username = “LeonDavisLD@outlook.com”;
  6. pop3.Password = “password”;
  7. pop3.Port = 995;
  8. pop3.EnableSsl = true;
  9. //Connect the pop server
  10. pop3.Connect();
  11. //Get the number of messages before deleting message(s)
  12. Pop3MessageInfoCollection messages = pop3.GetAllMessages();
  13. Console.WriteLine(“Number of messages before deleting: “ + messages.Count);
  14. //Delete an email message by its sequence number
  15. pop3.DeleteMessage(2);
  16. //Delete all messages
  17. //pop3.DeleteAllMessages();
  18. //Get the number of messages after deleting message(s)
  19. messages = pop3.GetAllMessages();
  20. Console.WriteLine(“Number of messages after deleting: “ + messages.Count);
Sending, Receiving And Deleting Emails In C#
Sending, Receiving And Deleting Emails In C#


This blog only illustrates the send, receive and delete email functions using c#. The Spire.Email component has rich features such as search email messages, add and extract attachment, get the mailbox and message information, and manipulate folders etc. And it supports c#, vb.net, asp.net applications, you can try it yourself.

Async And Await In C#

Nowadays, Asynchronous programming is very popular with the help of the async and await keywords in C#.

When we are dealing with UI and on button click, we use a long running method like reading a large file or something else which will take a long time, in that case, the entire application must wait to complete the whole task.

In other words, if any process is blocked in a synchronous application, the entire application gets blocked and our application stops responding until the whole task completes.

Asynchronous programming is very helpful in this condition. By using Asynchronous programming, the Application can continue with the other work that does not depend on the completion of the whole task.

We will get all the benefits of traditional Asynchronous programming with much less effort by the help of async and await keywords.

Suppose, we are using two methods as Method1 and Method2 respectively and both the methods are not dependent on each other and Method1 is taking a long time to complete its task. In Synchronous programming, it will execute the first Method1 and it will wait for completion of this method and then it will execute Method2. Thus, it will be a time intensive process even though both the methods are not depending on each other.

We can run all the methods parallelly by using the simple thread programming but it will block UI and wait to complete all the tasks. To come out of this problem, we have to write too many codes in traditional programming but if we will simply use the async and await keywords, then we will get the solutions in much less code.

Also, we are going to see more examples, if any third Method as Method3 has a dependency of method1, then it will wait for the completion of Method1 with the help of await keyword.

Async and await are the code markers, which marks code positions from where the control should resume after a task completes.

Let’s start with practical examples for understanding the programming concept.

Sample examples of async and await keyword in C#

We are going to take a console Application for our demonstration.

Example 1

In this example, we are going to take two methods, which are not dependent on each other.

Code sample

  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             Method1();
  6.             Method2();
  7.             Console.ReadKey();
  8.         }
  9.         public static async Task Method1()
  10.         {
  11.             await Task.Run(() =>
  12.             {
  13.                 for (int i = 0; i < 100; i++)
  14.                 {
  15.                     Console.WriteLine(” Method 1″);
  16.                 }
  17.             });
  18.         }
  19. public static void Method2()
  20.         {
  21.             for (int i = 0; i < 25; i++)
  22.             {
  23.                 Console.WriteLine(” Method 2″);
  24.             }
  25.         }
  26. }

In the code given above, Method1 and Method2 are not dependent on each other and we are calling from the Main method.

Here, we can clearly see Method1 and Method2 are not waiting for each other.

Now, coming to the second example, suppose we have Method3, which is dependent on Method1

Example 2

In this example, Method1 is returning total length as an integer value and we are passing a parameter as a length in a Method3, which is coming from Method1.

Here, we have to use await keyword before passing a parameter in Method3 and for it, we have to use the async keyword from the calling method.

We can not use await keyword without async and we cannot use async keyword in the Main method for the console Application because it will give the error given below.

We are going to create a new method as callMethod and in this method, we are going to call our all Methods as Method1, Method2 and Method3 respectively.

Code sample

  1. class Program
  2. s    {
  3.         static void Main(string[] args)
  4.         {
  5.             callMethod();
  6.             Console.ReadKey();
  7.         }
  8.         public static async void callMethod()
  9.         {
  10.             Task<int> task = Method1();
  11.             Method2();
  12.             int count = await task;
  13.             Method3(count);
  14.         }
  15.         public static async Task<int> Method1()
  16.         {
  17.             int count = 0;
  18.             await Task.Run(() =>
  19.             {
  20.                 for (int i = 0; i < 100; i++)
  21.                 {
  22.                     Console.WriteLine(” Method 1″);
  23.                     count += 1;
  24.                 }
  25.             });
  26.             return count;
  27.         }
  28.        public static void Method2()
  29.         {
  30.             for (int i = 0; i < 25; i++)
  31.             {
  32.                 Console.WriteLine(” Method 2″);
  33.             }
  34.         }
  35.         public static void Method3(int count)
  36.         {
  37.             Console.WriteLine(“Total count is “ + count);
  38.         }
  39. }

In the code given above, Method3 requires one parameter, which is the return type of Method1. Here, await keyword is playing a vital role for waiting of Method1 task completion.

Real time example

There are some supporting API’s from the .NET Framework 4.5 and the Windows runtime contains methods that support async programming.

We can use all of these in the real time project with the help of async and await keyword for the faster execution of the task.

Some APIs that contain async methods are HttpClient, SyndicationClient, StorageFile, StreamWriter, StreamReader, XmlReader, MediaCapture, BitmapEncoder, BitmapDecoder etc.

In this example, we are going to read all the characters from a large text file asynchronously and get the total length of all the characters.

Sample code

  1. class Program
  2.     {
  3.         static void Main()
  4.         {
  5.             Task task = new Task(CallMethod);
  6.             task.Start();
  7.             task.Wait();
  8.             Console.ReadLine();
  9.         }
  10.         static async void CallMethod()
  11.         {
  12.             string filePath = “E:\\sampleFile.txt”;
  13.             Task<int> task = ReadFile(filePath);
  14.             Console.WriteLine(” Other Work 1″);
  15.             Console.WriteLine(” Other Work 2″);
  16.             Console.WriteLine(” Other Work 3″);
  17.             int length = await task;
  18.             Console.WriteLine(” Total length: “ + length);
  19.             Console.WriteLine(” After work 1″);
  20.             Console.WriteLine(” After work 2″);
  21.         }
  22.         static async Task<int> ReadFile(string file)
  23.         {
  24.             int length = 0;
  25.             Console.WriteLine(” File reading is stating”);
  26.             using (StreamReader reader = new StreamReader(file))
  27.             {
  28.                 // Reads all characters from the current position to the end of the stream asynchronously
  29.                 // and returns them as one string.
  30.                 string s = await reader.ReadToEndAsync();
  31.                 length = s.Length;
  32.             }
  33.             Console.WriteLine(” File reading is completed”);
  34.             return length;
  35.         }
  36. }

In the code given above, we are calling a ReadFile method to read the contents of a text file and get the length of the total characters present in the text file.

In our sampleText.txt, file contains too many characters, so It will take a long time to read all the characters.

Here, we are using async programming to read all the contents from the file, so it will not wait to get a return value from this method and execute the other lines of code but it has to wait for the line of code given below because we are using await keyword and we are going to use the return value for the line of code given below..

  1. int length = await task;
  2.             Console.WriteLine(” Total length: “ + length);

Subsequently, other lines of code will be executed sequentially.

  1. Console.WriteLine(” After work 1″);
  2.             Console.WriteLine(” After work 2″);


Here, we have to understand very important points that if we are not using await keyword, then the method works as a synchronous method. The compiler will show the warning to us but it will not show any error.

In this easy way, we can use async and await keywords for Asynchronous programming in C#.

Iterators in C#

In the previous article we have discussed on Enumerable classes and enumerators and the difference between IEnumerator and IEnumerable Interface in C#. You can understand Enumerators here.

C# language provides a construct for creating Enumerators and Enumerables in simpler way and that is Iterator.By using Iterators, compiler will create Enumerators and Enumerables for you. You can use the enumerators and enumerables generated by iterators wherever you would use manually coded enumerators orenumerables.Iterators require the System.Collections.Generic namespace.

Let’s look at below example.

The following method declaration is another version that produces the same result:
Return an enumerator that returns strings.

you might have the feeling that something is different about this code. It doesn’t seem quite right. What exactly does the yield return statement do?

For example, in the first version, if the method returns on the first yield return statement, then the last two statements can never be reached. If it doesn’t return on the first statement, but continues through to the end of the method, then what happens to the values?

And in the second version, if the yield return statement in the body of the loop returns on the first iteration, then the loop will never get to any subsequent iterations. And besides all that, an enumerator doesn’t just return all the elements in one shot—it returns a new value with each access of the Current property. So, how does this give you an enumerator? Clearly this code is different from anything shown before.

Let’s understand the iterator blocks and yield statements to answer all these questions.

Iterator Blocks:

An iterator block is a code block with one or more yield statements. There are 3 types of Iterator blocks.

  • A method body
  • An accessor body
  • An operator body

In regular code blocks, the first statement in the block is executed, followed by the subsequent statements, and eventually control leaves the block but in iterator block,it describes the behavior of the enumerator class you want the compiler to build for you and it describes how to enumerate the elements.

Iterator blocks have two special statements:
• The yield return statement specifies the next item in the sequence to return.
• The yield break statement specifies that there are no more items in the sequence.

You can have the iterator produce either an enumerator or an enumerable depending on the return type you use for the iterator block.

Using an Iterator to Create an Enumerator:




  • Method Color is an iterator block that produces a method that returns an enumerator for class MyClass.
  • MyClass also implements method GetEnumerator, which just calls Color, and returns the enumerator that Color returns to it.
  • In Main, you can use an instance of the class directly in the foreach statement since the class implements GetEnumerator and is therefore enumerable.

Using an Iterator to Create an Enumerable:


black red white black red white


  • In the previous example, iterator method Color returned an IEnumerator, and MyClass implemented method GetEnumerator by returning the object created by Color.
  • In this example, the iterator method Color returns an IEnumerable rather than an IEnumerator. MyClass, therefore,implements its GetEnumerator method by first calling method Colors to get the enumerable object and then calling that object’s GetEnumerator method and returning its results.
  • Notice that in the foreach statement in Main, you can either use an instance of the class or call Color directly, since it returns an enumerable.

Common Iterator Patterns

Mainly there are 2 Iterator Patterns.
1.Enumerator Iterator Patterns
2.Enumerable Iterator Patterns
When you implement an iterator that returns an enumerator, you must make the class enumerable by implementing GetEnumerator

    • In a class, when you implement an iterator that returns an enumerable, you can make this class itself enumerable.

− If you implement GetEnumerator, make it call the iterator method to get an instance of the automatically generated class that implements IEnumerable.Next, return the enumerator built by GetEnumerator from this IEnumerable object
− If you decide against making the class itself enumerable, by not implementing GetEnumerator, you can still use the enumerable returned by the iterator, by calling the iterator method directly.

Creating Multiple Enumerables


Iterators as Properties:



In the above example,

  • It uses iterators to produce a class with two enumerators.
  • It shows how iterators can be implemented as properties rather than methods.
  • The code declares two properties that define two different enumerators. The GetEnumerator method returns one or the other of the two enumerators, depending on the value of the Boolean variable _listFromUVtoIR. If _listFromUVtoIR is true, then the UVtoIR enumerator is returned. Otherwise, the IRtoUV enumerator is returned.

Behind the Scenes with Iterators in C#

The enumerator class generated by the compiler is a state machine with four states:
• Before: The initial state before the first call to MoveNext.
• Running: The state entered when MoveNext is called. In this state, the enumerator determines and sets the position for the next item. It exits the state when it encounters a yield return, a yield break, or the end of the iterator body.
• Suspended: The state where the state machine is waiting for the next call to MoveNext.
• After: The state where there are no more items to enumerate.


In this article, we have discussed:

  • Iterators in C#
  • Iterator Blocks
  • Yield Statements
  • Using an Iterator to Create an Enumerator
  • Using an Iterator to Create an Enumerable
  • Common Iterator Patterns
  • Creating Multiple Enumerables
  • Iterators As Properties
  • Behind the Scenes with Iterators
  • Iterator StateMachine
  • An Iterator state machine

solid design principles c#

Developers start building applications with good and tidy designs using their knowledge and experience. But over time, applications might develop bugs. The application design must be altered for every change request or new feature request. After some time we might need to put in a lot of effort, even for simple tasks and it might require a full working knowledge of the entire system. But we can’t blame change or new feature requests. They are part of the software development. We can’t stop them and refuse them either. So who is the culprit here? Obviously it is the design of the application.

The following are the design flaws that cause the damage in software, mostly.

  1. Putting more stress on classes by assigning more responsibilities to them. (A lot of functionality not related to a class.)
  2. Forcing the classes to depend on each other. If classes are dependent on each other (in other words tightly coupled), then a change in one will affect the other.
  3. Spreading duplicate code in the system/application.


  1. Choosing the correct architecture (in other words MVC, 3-tier, Layered, MVP, MVVP and so on).
  2. Following Design Principles.
  3. Choosing correct Design Patterns to build the software based on it’s specifications.

Now we go through the Design Principles first and will cover the rest soon.

Intro to SOLID principles

SOLID principles are the design principles that enable us to manage with most of the software design problems. Robert C. Martin compiled these principles in the 1990s. These principles provide us ways to move from tightly coupled code and little encapsulation to the desired results of loosely coupled and encapsulated real needs of a business properly. SOLID is an acronym of the following.

  • S: Single Responsibility Principle (SRP)
  • O: Open closed Principle (OSP)
  • L: Liskov substitution Principle (LSP)
  • I: Interface Segregation Principle (ISP)
  • D: Dependency Inversion Principle (DIP)

S: Single Responsibility Principle (SRP) 

SRP says “Every software module should have only one reason to change”.

This means that every class, or similar structure, in your code should have only one job to do. Everything in that class should be related to a single purpose. Our class should not be like a Swiss knife wherein if one of them needs to be changed then the entire tool needs to be altered. It does not mean that your classes should only contain one method or property. There may be many members as long as they relate to the single responsibility.

The Single Responsibility Principle gives us a good way of identifying classes at the design phase of an application and it makes you think of all the ways a class can change. A good separation of responsibilities is done only when the full picture of how the application should work. Let us check this with an example.

  1. public class UserService
  2. {
  3.    public void Register(string email, string password)
  4.    {
  5.       if (!ValidateEmail(email))
  6.          throw new ValidationException(“Email is not an email”);
  7.          var user = new User(email, password);
  8.          SendEmail(new MailMessage(“mysite@nowhere.com”, email) { Subject=“HEllo foo” });
  9.    }
  10.    public virtual bool ValidateEmail(string email)
  11.    {
  12.      return email.Contains(“@”);
  13.    }
  14.    public bool SendEmail(MailMessage message)
  15.    {
  16.      _smtpClient.Send(message);
  17.    }
  18. }

It looks fine, but it is not following SRP. The SendEmail and ValidateEmail methods have nothing to do within the UserService class. Let’s refract it.

  1. public class UserService
  2. {
  3.    EmailService _emailService;
  4.    DbContext _dbContext;
  5.    public UserService(EmailService aEmailService, DbContext aDbContext)
  6.    {
  7.       _emailService = aEmailService;
  8.       _dbContext = aDbContext;
  9.    }
  10.    public void Register(string email, string password)
  11.    {
  12.       if (!_emailService.ValidateEmail(email))
  13.          throw new ValidationException(“Email is not an email”);
  14.          var user = new User(email, password);
  15.          _dbContext.Save(user);
  16.          emailService.SendEmail(new MailMessage(“myname@mydomain.com”, email) {Subject=“Hi. How are you!”});
  17.       }
  18.    }
  19.    public class EmailService
  20.    {
  21.       SmtpClient _smtpClient;
  22.    public EmailService(SmtpClient aSmtpClient)
  23.    {
  24.       _smtpClient = aSmtpClient;
  25.    }
  26.    public bool virtual ValidateEmail(string email)
  27.    {
  28.       return email.Contains(“@”);
  29.    }
  30.    public bool SendEmail(MailMessage message)
  31.    {
  32.       _smtpClient.Send(message);
  33.    }
  34. }

O: Open/Closed Principle

The Open/closed Principle says “A software module/class is open for extension and closed for modification”.

Here “Open for extension” means, we need to design our module/class in such a way that the new functionality can be added only when new requirements are generated. “Closed for modification” means we have already developed a class and it has gone through unit testing. We should then not alter it until we find bugs. As it says, a class should be open for extensions, we can use inheritance to do this. Okay, let’s dive into an example.

Suppose we have a Rectangle class with the properties Height and Width.

  1. public class Rectangle{
  2.    public double Height {get;set;}
  3.    public double Wight {get;set; }
  4. }

Our app needs the ability to calculate the total area of a collection of Rectangles. Since we already learned the Single Responsibility Principle (SRP), we don’t need to put the total area calculation code inside the rectangle. So here I created another class for area calculation.

  1. public class AreaCalculator {
  2.    public double TotalArea(Rectangle[] arrRectangles)
  3.    {
  4.       double area;
  5.       foreach(var objRectangle in arrRectangles)
  6.       {
  7.          area += objRectangle.Height * objRectangle.Width;
  8.       }
  9.       return area;
  10.    }
  11. }

Hey, we did it. We made our app without violating SRP. No issues for now. But can we extend our app so that it could calculate the area of not only Rectangles but also the area of Circles as well? Now we have an issue with the area calculation issue, because the way to do circle area calculation is different. Hmm. Not a big deal. We can change the TotalArea method a bit, so that it can accept an array of objects as an argument. We check the object type in the loop and do area calculation based on the object type.

  1. public class Rectangle{
  2.    public double Height {get;set;}
  3.    public double Wight {get;set; }
  4. }
  5. public class Circle{
  6.    public double Radius {get;set;}
  7. }
  8. public class AreaCalculator
  9. {
  10.    public double TotalArea(object[] arrObjects)
  11.    {
  12.       double area = 0;
  13.       Rectangle objRectangle;
  14.       Circle objCircle;
  15.       foreach(var obj in arrObjects)
  16.       {
  17.          if(obj is Rectangle)
  18.          {
  19.             objRectangle = (Rectangle)obj;
  20.             area += obj.Height * obj.Width;
  21.          }
  22.          else
  23.          {
  24.             objCircle = (Circle)obj;
  25.             area += objCircle.Radius * objCircle.Radius * Math.PI;
  26.          }
  27.       }
  28.       return area;
  29.    }
  30. }

Wow. We are done with the change. Here we successfully introduced Circle into our app. We can add a Triangle and calculate it’s area by adding one more “if” block in the TotalArea method of AreaCalculator. But every time we introduce a new shape we need to alter the TotalArea method. So the AreaCalculator class is not closed for modification. How can we make our design to avoid this situation? Generally we can do this by referring to abstractions for dependencies, such as interfaces or abstract classes, rather than using concrete classes. Such interfaces can be fixed once developed so the classes that depend upon them can rely upon unchanging abstractions. Functionality can be added by creating new classes that implement the interfaces. So let’s refract our code using an interface.

  1. public abstract class Shape
  2. {
  3.    public abstract double Area();
  4. }

Inheriting from Shape, the Rectangle and Circle classes now look like this:

  1. public class Rectangle: Shape
  2. {
  3.    public double Height {get;set;}
  4.    public double Width {get;set;}
  5.    public override double Area()
  6.    {
  7.       return Height * Width;
  8.    }
  9. }
  10. public class Circle: Shape
  11. {
  12.    public double Radius {get;set;}
  13.    public override double Area()
  14.    {
  15.       return Radius * Radus * Math.PI;
  16.    }
  17. }

Every shape contains its area show with it’s own way of calculation functionality and our AreaCalculator class will become simpler than before.

  1. public class AreaCalculator
  2. {
  3.    public double TotalArea(Shape[] arrShapes)
  4.    {
  5.       double area=0;
  6.       foreach(var objShape in arrShapes)
  7.       {
  8.          area += objShape.Area();
  9.       }
  10.       return area;
  11.    }
  12. }

Now our code is following SRP and OCP both. Whenever you introduce a new shape by deriving from the “Shape” abstract class, you need not change the “AreaCalculator” class. Awesome. Isn’t it?

L: Liskov substitution Principle

The Liskov Substitution Principle (LSP) states that “you should be able to use any derived class instead of a parent class and have it behave in the same manner without modification”. It ensures that a derived class does not affect the behavior of the parent class, in other words that a derived class must be substitutable for its base class.

This principle is just an extension of the Open Close Principle and it means that we must ensure that new derived classes extend the base classes without changing their behavior. I will explain this with a real world example that violates LSP.

A father is a doctor whereas his son wants to become a cricketer. So here the son can’t replace his father even though they both belong to the same family hierarchy.

Now jump into an example to learn how a design can violate LSP. Suppose we need to build an app to manage data using a group of SQL files text. Here we need to write functionality to load and save the text of a group of SQL files in the application directory. So we need a class that manages the load and save of the text of group of SQL files along with the SqlFile Class.

  1. public class SqlFile
  2. {
  3.    public string FilePath {get;set;}
  4.    public string FileText {get;set;}
  5.    public string LoadText()
  6.    {
  7.       /* Code to read text from sql file */
  8.    }
  9.    public string SaveText()
  10.    {
  11.       /* Code to save text into sql file */
  12.    }
  13. }
  14. public class SqlFileManager
  15. {
  16.    public List<SqlFile> lstSqlFiles {get;set}
  17.    public string GetTextFromFiles()
  18.    {
  19.       StringBuilder objStrBuilder = new StringBuilder();
  20.       foreach(var objFile in lstSqlFiles)
  21.       {
  22.          objStrBuilder.Append(objFile.LoadText());
  23.       }
  24.       return objStrBuilder.ToString();
  25.    }
  26.    public void SaveTextIntoFiles()
  27.    {
  28.       foreach(var objFile in lstSqlFiles)
  29.       {
  30.          objFile.SaveText();
  31.       }
  32.    }
  33. }

OK. We are done with our part. the functionality looks good for now. After some time our lead might tell us that we may have a few read-only files in the application folder, so we need to restrict the flow whenever it tries to do a save on them.

OK. We can do that by creating a “ReadOnlySqlFile” class that inherits the “SqlFile” class and we need to alter the SaveTextIntoFiles() method by introducing a condition to prevent calling the SaveText() method on ReadOnlySqlFile instances.

  1. public class SqlFile
  2. {
  3.    public string LoadText()
  4.    {
  5.    /* Code to read text from sql file */
  6.    }
  7.    public void SaveText()
  8.    {
  9.       /* Code to save text into sql file */
  10.    }
  11. }
  12. public class ReadOnlySqlFile: SqlFile
  13. {
  14.    public string FilePath {get;set;}
  15.    public string FileText {get;set;}
  16.    public string LoadText()
  17.    {
  18.       /* Code to read text from sql file */
  19.    }
  20.    public void SaveText()
  21.    {
  22.       /* Throw an exception when app flow tries to do save. */
  23.       throw new IOException(“Can’t Save”);
  24.    }
  25. }

To avoid an exception we need to modify “SqlFileManager” by adding one condition to the loop.

  1. public class SqlFileManager
  2. {
  3.    public List<SqlFile? lstSqlFiles {get;set}
  4.    public string GetTextFromFiles()
  5.    {
  6.       StringBuilder objStrBuilder = new StringBuilder();
  7.       foreach(var objFile in lstSqlFiles)
  8.       {
  9.          objStrBuilder.Append(objFile.LoadText());
  10.       }
  11.       return objStrBuilder.ToString();
  12.    }
  13.    public void SaveTextIntoFiles()
  14.    {
  15.       foreach(var objFile in lstSqlFiles)
  16.       {
  17.          //Check whether the current file object is read only or not.If yes, skip calling it’s
  18.          // SaveText() method to skip the exception.
  19.          if(! objFile is ReadOnlySqlFile)
  20.          objFile.SaveText();
  21.       }
  22.    }
  23. }

Here we altered the SaveTextIntoFiles() method in the SqlFileManager class to determine whether or not the instance is of ReadOnlySqlFile to avoid the exception. We can’t use this ReadOnlySqlFile class as a substitute of it’s parent without altering SqlFileManager code. So we can say that this design is not following LSP. Let’s make this design follow the LSP. Here we will introduce interfaces to make the SqlFileManager class independent from the rest of the blocks.

  1. public interface IReadableSqlFile
  2. {
  3.    string LoadText();
  4. }
  5. public interface IWritableSqlFile
  6. {
  7.    void SaveText();
  8. }

Now we implement IReadableSqlFile through the ReadOnlySqlFile class that reads only the text from read-only files.

  1. public class ReadOnlySqlFile: IReadableSqlFile
  2. {
  3.    public string FilePath {get;set;}
  4.    public string FileText {get;set;}
  5.    public string LoadText()
  6.    {
  7.       /* Code to read text from sql file */
  8.    }
  9. }

Here we implement both IWritableSqlFile and IReadableSqlFile in a SqlFile class by which we can read and write files.

  1. public class SqlFile: IWritableSqlFile,IReadableSqlFile
  2. {
  3.    public string FilePath {get;set;}
  4.    public string FileText {get;set;}
  5.    public string LoadText()
  6.    {
  7.       /* Code to read text from sql file */
  8.    }
  9.    public void SaveText()
  10.    {
  11.       /* Code to save text into sql file */
  12.    }
  13. }

Now the design of the SqlFileManager class becomes like this:

  1. public class SqlFileManager
  2. {
  3.    public string GetTextFromFiles(List<IReadableSqlFile> aLstReadableFiles)
  4.    {
  5.       StringBuilder objStrBuilder = new StringBuilder();
  6.       foreach(var objFile in aLstReadableFiles)
  7.       {
  8.          objStrBuilder.Append(objFile.LoadText());
  9.       }
  10.       return objStrBuilder.ToString();
  11.    }
  12.    public void SaveTextIntoFiles(List<IWritableSqlFile> aLstWritableFiles)
  13.    {
  14.    foreach(var objFile in aLstWritableFiles)
  15.    {
  16.       objFile.SaveText();
  17.    }
  18.    }
  19. }

Here the GetTextFromFiles() method gets only the list of instances of classes that implement the IReadOnlySqlFile interface. That means the SqlFile and ReadOnlySqlFile class instances. And the SaveTextIntoFiles() method gets only the list instances of the class that implements the IWritableSqlFiles interface, in other words SqlFile instances in this case. Now we can say our design is following the LSP. And we fixed the problem using the Interface segregation principle by (ISP) identifying the abstraction and the responsibility separation method.

I: Interface Segregation Principle (ISP)

The Interface Segregation Principle states “that clients should not be forced to implement interfaces they don’t use. Instead of one fat interface many small interfaces are preferred based on groups of methods, each one serving one sub module.”.

We can define it in another way. An interface should be more closly related to the code that uses it than code that implements it. So the methods on the interface are defined by which methods the client code needs than which methods the class implements. So clients should not be forced to depend upon interfaces that they don’t use.

Like classes, each interface should have a specific purpose/responsibility (refer to SRP). You shouldn’t be forced to implement an interface when your object doesn’t share that purpose. The larger the interface, the more likely it includes methods that not all implementers can do. That’s the essence of the Interface Segregation Principle. Let’s start with an example that breaks ISP. Suppose we need to build a system for an IT firm that contains roles like TeamLead and Programmer where TeamLead divides a huge task into smaller tasks and assigns them to his/her programmers or can directly work on them.

Based on specifications, we need to create an interface and a TeamLead class to implement it.

  1. public Interface ILead
  2. {
  3.    void CreateSubTask();
  4.    void AssginTask();
  5.    void WorkOnTask();
  6. }
  7. public class TeamLead : ILead
  8. {
  9.    public void AssignTask()
  10.    {
  11.       //Code to assign a task.
  12.    }
  13.    public void CreateSubTask()
  14.    {
  15.       //Code to create a sub task
  16.    }
  17.    public void WorkOnTask()
  18.    {
  19.       //Code to implement perform assigned task.
  20.    }
  21. }

OK. The design looks fine for now. Later another role like Manager, who assigns tasks to TeamLead and will not work on the tasks, is introduced into the system. Can we directly implement an ILead interface in the Manager class, like the following?

  1. public class Manager: ILead
  2. {
  3.    public void AssignTask()
  4.    {
  5.       //Code to assign a task.
  6.    }
  7.    public void CreateSubTask()
  8.    {
  9.       //Code to create a sub task.
  10.    }
  11.    public void WorkOnTask()
  12.    {
  13.       throw new Exception(“Manager can’t work on Task”);
  14.    }
  15. }

Since the Manager can’t work on a task and at the same time no one can assign tasks to the Manager, this WorkOnTask() should not be in the Manager class. But we are implementing this class from the ILead interface, we need to provide a concrete Method. Here we are forcing the Manager class to implement a WorkOnTask() method without a purpose. This is wrong. The design violates ISP. Let’s correct the design.

Since we have three roles, 1. Manager, that can only divide and assign the tasks , 2. TeamLead that can divide and assign the tasks and can work on them as well, 3. Programmer that can only work on tasks, we need to divide the responsibilities by segregating the ILead interface. An interface that provides a contract for WorkOnTask().

  1. public interface IProgrammer
  2. {
  3.    void WorkOnTask();
  4. }

An interface that provide contracts to manage the tasks:

  1. public interface ILead
  2. {
  3.    void AssignTask();
  4.    void CreateSubTask();
  5. }

Then the implementation becomes:

  1. public class Programmer: IProgrammer
  2. {
  3.    public void WorkOnTask()
  4.    {
  5.       //code to implement to work on the Task.
  6.    }
  7. }
  8. public class Manager: ILead
  9. {
  10.    public void AssignTask()
  11.    {
  12.       //Code to assign a Task
  13.    }
  14.    public void CreateSubTask()
  15.    {
  16.    //Code to create a sub taks from a task.
  17.    }
  18. }

TeamLead can manage tasks and can work on them if needed. Then the TeamLead class should implement both of the IProgrammer and ILead interfaces.

  1. public class TeamLead: IProgrammer, ILead
  2. {
  3.    public void AssignTask()
  4.    {
  5.       //Code to assign a Task
  6.    }
  7.    public void CreateSubTask()
  8.    {
  9.       //Code to create a sub task from a task.
  10.    }
  11.    public void WorkOnTask()
  12.    {
  13.       //code to implement to work on the Task.
  14.    }
  15. }

Wow. Here we separated responsibilities/purposes and distributed them on multiple interfaces and provided a good level of abstraction too.

D: Dependency Inversion Principle

The Dependency Inversion Principle (DIP) states that high-level modules/classes should not depend upon low-level modules/classes. Both should depend upon abstractions. Secondly, abstractions should not depend upon details. Details should depend upon abstractions.

High-level modules/classes implement business rules or logic in a system (application). Low-level modules/classes deal with more detailed operations, in other words they may deal with writing information to databases or passing messages to the operating system or services.

A high-level module/class that has dependency on low-level modules/classes or some other class and knows a lot about the other classes it interacts with is said to be tightly coupled. When a class knows explicitly about the design and implementation of another class, it raises the risk that changes to one class will break the other class. So we must keep these high-level and low-level modules/class loosely coupled as much as we can. To do that, we need to make both of them dependent on abstractions instead of knowing each other. Let’s start an with an example.

Suppose we need to work on an error logging module that logs exception stack traces into a file. Simple, isn’t it? The following are the classes that provide functionality to log a stack trace into a file.

  1. public class FileLogger
  2. {
  3.    public void LogMessage(string aStackTrace)
  4.    {
  5.       //code to log stack trace into a file.
  6.    }
  7. }
  8. public class ExceptionLogger
  9. {
  10.    public void LogIntoFile(Exception aException)
  11.    {
  12.       FileLogger objFileLogger = new FileLogger();
  13.       objFileLogger.LogMessage(GetUserReadableMessage(aException));
  14.    }
  15.    private GetUserReadableMessage(Exception ex)
  16.    {
  17.       string strMessage = string. Empty;
  18.       //code to convert Exception’s stack trace and message to user readable format.
  19.       ….
  20.       ….
  21.       return strMessage;
  22.    }
  23. }

A client class exports data from many files to a database.

  1. public class DataExporter
  2. {
  3.    public void ExportDataFromFile()
  4.    {
  5.    try {
  6.       //code to export data from files to database.
  7.    }
  8.    catch(Exception ex)
  9.    {
  10.       new ExceptionLogger().LogIntoFile(ex);
  11.    }
  12. }
  13. }

Looks good. We sent our application to the client. But our client wants to store this stack trace in a database if an IO exception occurs. Hmm… okay, no problem. We can implement that too. Here we need to add one more class that provides the functionality to log the stack trace into the database and an extra method in ExceptionLogger to interact with our new class to log the stack trace.

  1. public class DbLogger
  2. {
  3.    public void LogMessage(string aMessage)
  4.    {
  5.       //Code to write message in database.
  6.    }
  7. }
  8. public class FileLogger
  9. {
  10.    public void LogMessage(string aStackTrace)
  11.    {
  12.       //code to log stack trace into a file.
  13.    }
  14. }
  15. public class ExceptionLogger
  16. {
  17.    public void LogIntoFile(Exception aException)
  18.    {
  19.       FileLogger objFileLogger = new FileLogger();
  20.       objFileLogger.LogMessage(GetUserReadableMessage(aException));
  21.    }
  22.    public void LogIntoDataBase(Exception aException)
  23.    {
  24.       DbLogger objDbLogger = new DbLogger();
  25.       objDbLogger.LogMessage(GetUserReadableMessage(aException));
  26.    }
  27.    private string GetUserReadableMessage(Exception ex)
  28.    {
  29.       string strMessage = string.Empty;
  30.       //code to convert Exception’s stack trace and message to user readable format.
  31.       ….
  32.       ….
  33.       return strMessage;
  34.    }
  35. }
  36. public class DataExporter
  37. {
  38.    public void ExportDataFromFile()
  39.    {
  40.       try {
  41.          //code to export data from files to database.
  42.       }
  43.       catch(IOException ex)
  44.       {
  45.          new ExceptionLogger().LogIntoDataBase(ex);
  46.       }
  47.       catch(Exception ex)
  48.       {
  49.          new ExceptionLogger().LogIntoFile(ex);
  50.       }
  51.    }
  52. }

Looks fine for now. But whenever the client wants to introduce a new logger, we need to alter ExceptionLogger by adding a new method. If we continue doing this after some time then we will see a fat ExceptionLogger class with a large set of methods that provide the functionality to log a message into various targets. Why does this issue occur? Because ExceptionLogger directly contacts the low-level classes FileLogger and and DbLogger to log the exception. We need to alter the design so that this ExceptionLogger class can be loosely coupled with those class. To do that we need to introduce an abstraction between them, so that ExcetpionLogger can contact the abstraction to log the exception instead of depending on the low-level classes directly.

  1. public interface ILogger
  2. {
  3.    public void LogMessage(string aString);
  4. }

Now our low-level classes need to implement this interface.

  1. public class DbLogger: ILogger
  2. {
  3.    public void LogMessage(string aMessage)
  4.    {
  5.       //Code to write message in database.
  6.    }
  7. }
  8. public class FileLogger: ILogger
  9. {
  10.    public void LogMessage(string aStackTrace)
  11.    {
  12.       //code to log stack trace into a file.
  13.    }
  14. }

Now, we move to the low-level class’s intitiation from the ExcetpionLogger class to the DataExporter class to make ExceptionLogger loosely coupled with the low-level classes FileLogger and EventLogger. And by doing that we are giving provision to DataExporter class to decide what kind of Logger should be called based on the exception that occurs.

  1. public class ExceptionLogger
  2. {
  3.    private ILogger _logger;
  4.    public ExceptionLogger(ILogger aLogger)
  5.    {
  6.       this._logger = aLogger;
  7.    }
  8.    public void LogException(Exception aException)
  9.    {
  10.       string strMessage = GetUserReadableMessage(aException);
  11.       this._logger.LogMessage(strMessage);
  12.    }
  13.    private string GetUserReadableMessage(Exception aException)
  14.    {
  15.       string strMessage = string.Empty;
  16.       //code to convert Exception’s stack trace and message to user readable format.
  17.       ….
  18.       ….
  19.       return strMessage;
  20.    }
  21. }
  22. public class DataExporter
  23. {
  24.    public void ExportDataFromFile()
  25.    {
  26.       ExceptionLogger _exceptionLogger;
  27.       try {
  28.          //code to export data from files to database.
  29.       }
  30.       catch(IOException ex)
  31.       {
  32.          _exceptionLogger = new ExceptionLogger(new DbLogger());
  33.          _exceptionLogger.LogException(ex);
  34.       }
  35.       catch(Exception ex)
  36.       {
  37.          _exceptionLogger = new ExceptionLogger(new FileLogger());
  38.          _exceptionLogger.LogException(ex);
  39.       }
  40.    }
  41. }

We successfully removed the dependency on low-level classes. This ExceptionLogger doesn’t depend on the FileLogger and EventLogger classes to log the stack trace. We don’t need to change the ExceptionLogger’s code any more for any new logging functionality. We need to create a new logging class that implements the ILogger interface and must add another catch block to the DataExporter class’s ExportDataFromFile method.

  1. public class EventLogger: ILogger
  2. {
  3.    public void LogMessage(string aMessage)
  4.    {
  5.       //Code to write message in system’s event viewer.
  6.    }
  7. }

And we need to add a condition in the DataExporter class as in the following:

  1. public class DataExporter
  2. {
  3.    public void ExportDataFromFile()
  4.    {
  5.       ExceptionLogger _exceptionLogger;
  6.       try {
  7.          //code to export data from files to database.
  8.       }
  9.       catch(IOException ex)
  10.       {
  11.          _exceptionLogger = new ExceptionLogger(new DbLogger());
  12.          _exceptionLogger.LogException(ex);
  13.       }
  14.       catch(SqlException ex)
  15.       {
  16.          _exceptionLogger = new ExceptionLogger(new EventLogger());
  17.          _exceptionLogger.LogException(ex);
  18.       }
  19.       catch(Exception ex)
  20.       {
  21.          _exceptionLogger = new ExceptionLogger(new FileLogger());
  22.          _exceptionLogger.LogException(ex);
  23.       }
  24.    }
  25. }

Looks good. But we introduced the dependency here in the DataExporter class’s catch blocks. Yeah, someone must take the responsibility to provide the necessary objects to the ExceptionLogger to make the work done.

Let me explain it with a real world example. Suppose we want to have a wooden chair with specific measurements and the kind of wood to be used to make that chair from. Then we can’t leave the decision making on measurements and the wood to the carpenter. Here his job is to make a chair based on our requirements with his tools and we provide the specifications to him to make a good chair.

So what is the benefit we get by the design? Yes, we definitely have a benefit with it. We need to modify both the DataExporter class and ExceptionLogger class whenever we need to introduce a new logging functionality. But in the updated design we need to add only another catch block for the new exception logging feature. Coupling is not inherently evil. If you don’t have some amount of coupling, your software will not do anything for you. The only thing we need to do is understand the system, requirements and environment properly and find areas where DIP should be followed.

Great, we have gone through the all five SOLID principles successfully. And we can conclude that using these principles we can build an application with tidy, readable and easily maintainable code.

Here you may have some doubt. Yes, about the quantity of code. Because of these principles, the code might become larger in our applications. But my dear friends, you need to compare it with the quality that we get by following these principles. Hmm, but anyway 27 lines are much less than 200 lines. I am not saying that these principles should be followed 100%, you need to draw a Yellow so that you can hold the control over the things like quality and delivery to maintain their balance.

This is my little effort to share the uses of SOLID principles. I hope you enjoyed this article.

Top 10 C# 6.0 Language Features

Static Using Syntax:

Before C# 6.0, In a console application if you wanted to print something, then you would write the following line of code:

In C# 6, you can now add the using static qualifier and reference the WriteLine method by itself as shown below:

This will also work for custom classes created by yourself. Let’s look at the below example.

Since you have declared CustomClass with the static keyword, you can run the method by just calling the method name. The output for this sample program would be :

2. String Interpolation :

String Interpolation is a mechanism to concatenate two or more strings together.In older versions of C#, we were using “+” operator or String.Format method to concatenate strings but in C# 6.0, Microsoft has provided a feature named String Interpolation to concatenate strings.

Using “+” Operator:

Using String.Format method:

New ways of String Concatenation in C#6.0

The output for this program will be:

3. Exception Filters:

Earlier Exception filters were supported in Visual Basic but not in C#. They allow you to specify a condition for a catch block.

In C#6.0, without entering the catch block, you can check to see which condition met your exception.

4. Await in a Catch and Finally Block:

In C# 6, now you can write asynchronous code inside a catch/finally block. This will help you to log exceptions to a file or database without blocking the current thread. Let’s look at below example:

5. Null Conditional Operator:

Most of us do not like NullReferenceException . Let’s look at below example, on how to handle NullReferenceException prior to C#6.0.

If you enter some data into name, then the console prints out that name else this returns “Field is null”.

New ways to handle NullReferenceException in C#6.0:

In C# 6.0, you can use ?. to check if an instance is null or not. Let’s look at below example to see how it works in C#6.0.

6. Auto Property Initializer:

Prior to C#6.0, we were using constructor to initialize the auto properties to non-default value.

In C#6.0, you can modify the Employee class and populate the property called EmployeeID with inline initialization.

The output for this sample will be a random guid generated by the system.

7. Dictionary Initializers:

In C# 5, you would initialize the Dictionary with a {“Key”, “Value”} Pair. Let’s look at below example to understand it better.

In C# 6, you can place the key between two square brackets [“Key”] and then set the value of the key [“Key”] = “value”.

8.Expression Bodied Function & Property:

Expression Bodied Functions are functions with no statement body. Instead, you implement them with an expression following the function declaration

The result of the above program would be 10.

9. Getter-only Auto Properties:

When you use auto implemented properties in C# 5 and lower, you must provide a get and set. If you want the property value to be immutable, you can use the private accessor on the setter. With C# 6, you can now omit the set accessor to achieve true readonly auto implemented properties:

10. NameOf Expression:

Name of Expression is a new feature introduced in C#6.0.In Enterprise level applications, we handle exceptions at different levels.Showing a specific type name with an error message can be an easy way to find the code block where the exception just occurred. But by adding this we can’t show it to user because the type name can be changed anytime while refactoring but hard coded string won’t change accordingly.

Before C# 6.0 :

What happens if someone changes the Title variable to newTitle? Since we hard-coded the “Title is null” error, that is what will appear to the end-user. We would rather it now say, “newTitle is null”, but the compiler cannot recognize this.

In C# 6.0, we can refactor our code to remove the string literals and use the nameof expression.


In this article, we have discussed top 10 new features introduced in C# 6.0.
– Auto Property Initializer
– Await in a Catch and Finally Block in C#6.0
– Dictionary Initializers in C# 6.0
– Exception Filters in C#6.0
– Expression Bodied Function & Property in C#6.0
– Getter-only Auto Properties in C#6.0
– NameOf Expression in C#6.0
– Null Conditional Operator in C#6.0
– Static Using Syntax in C#6.0
– String Interpolation in C#6.0

Thanks For visiting !!

C# 7.0 tuples

Tuple is an ordered sequence of heterogeneous objects. We may often write methods which return multiple values so we need to create a simple structure containing more than one data elements. To support these scenarios, tuples were added to C#. Tuples are lightweight data structures that contain multiple fields to represent the data members.

If a method returns multiple homogenous values, then it stores these values in the collection and returns that collection. But a method needs to return multiple heterogenous values, then C# provides some options such as Class/Struct, out parameter and Tuple.

Let’s create an example. We have a collection of integer numbers and we need to find out the minimum and maximum number from this collection. We need to create a method which returns both Minimum and Maximum values. To achieve this, we have three options which are Class/Struct, out parameter, and Tuple. So, let’s see each option one by one.

Using Out Parameter

As we create a method which finds the maximum and minimum number in the number series. This method has two values as a result of a maximum and minimum number. So, we create the method which returns a value and use out parameter as argument. The return value holds a maximum number from series while out parameter holds a minimum number from series.

Let’s create a class named Operation which holds a method to find a minimum and maximum number from number series. The following code snippet is for the same.

  1. using System.Collections.Generic;
  2. namespace TupleApp
  3. {
  4.     class Operation
  5.     {
  6.         internal int FindMinMax(List<int> list, out int min)
  7.         {
  8.             int maximum = int.MinValue, minimum = int.MaxValue;
  9.             list.ForEach(n =>
  10.             {
  11.                 minimum = n < minimum ? n : minimum;
  12.                 maximum = n > maximum ? n : maximum;
  13.             });
  14.             min = minimum;
  15.             return maximum;
  16.         }
  17.     }
  18. }

As per the above code snippet, the method returns a value which holds an in variable named maximum. That value is a maximum number from series. This method takes out parameter as an argument named min which holds a minimum value from series.

Now, call this method from an executable program as per the following code snippet.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using static System.Console;
  5. namespace TupleApp
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             List<int> numbers = Enumerable.Range(1, 100).OrderBy(x => Guid.NewGuid()).Take(10).ToList();
  12.             int minimum = 0, maximum = 0;
  13.             Operation operation = new Operation();
  14.             maximum = operation.FindMinMax(numbers, out minimum);
  15.             Write($“{minimum} is min and {maximum} is max in {String.Join(“,“, numbers)}”);
  16.             Read();
  17.         }
  18.     }
  19. }

Now, run the application. The result shows as in the below figure.

Figure 1: Output

It’s right approach but out parameter doesn’t work with async method.

Using Class/Struct

There is another option to get multiple values from a method – create a class or struct with that data structure. We perform the same operation here as well. We create a struct named CalculateData which has two properties to hold maximum and minimum number from a series. The following code snippet is used for the same struct.

  1. namespace TupleApp
  2. {
  3.     struct CalculateData
  4.     {
  5.         public int Minimum { get; set; }
  6.         public int Maximum { get; set; }
  7.     }
  8. }

Now, let’s create another class named Operation which holds a method to find a minimum and maximum number from number series. The following code snippet can be used for the same.

  1. using System.Collections.Generic;
  2. namespace TupleApp
  3. {
  4.     class Operation
  5.     {
  6.         internal CalculateData FindMinMax(List<int> list)
  7.         {
  8.             int maximum = int.MinValue, minimum = int.MaxValue;
  9.             list.ForEach(n =>
  10.             {
  11.                 minimum = n < minimum ? n : minimum;
  12.                 maximum = n > maximum ? n : maximum;
  13.             });
  14.             CalculateData data = new CalculateData
  15.             {
  16.                 Minimum = minimum,
  17.                 Maximum = maximum
  18.             };
  19.             return data;
  20.         }
  21.     }
  22. }

As per the above code snippet, the method returns an object which has two properties. These properties hold maximum and minimum values from series.

Now, call this method from an executable program, as per the following code snippet.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using static System.Console;
  5. namespace TupleApp
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             List<int> numbers = Enumerable.Range(1, 100).OrderBy(x => Guid.NewGuid()).Take(10).ToList();
  12.             Operation operation = new Operation();
  13.             CalculateData data = operation.FindMinMax(numbers);
  14.             Write($“{data.Minimum} is min and {data.Maximum} is max in {String.Join(“,“, numbers)}”);
  15.             Read();
  16.         }
  17.     }
  18. }

Now, run the application. The end result shows as in the below figure.

Figure 2: Output

Using Tuple

The C# 7 introduced a new way to define Tuple. Tuple is another option to get multiple values from a method. It can hold multiple heterogeneous values. To use Tuple in the application, we need to install System.ValueTuple NuGet package.

We perform the same operation here as well. Let’s create a class named Operation which holds a method to find a minimum and maximum number from number series. The following code snippet is used for the same.

  1. using System.Collections.Generic;
  2. namespace TupleApp
  3. {
  4.     class Operation
  5.     {
  6.         internal (intint) FindMinMax(List<int> list)
  7.         {
  8.             int maximum = int.MinValue, minimum = int.MaxValue;
  9.             list.ForEach(n =>
  10.             {
  11.                 minimum = n < minimum ? n : minimum;
  12.                 maximum = n > maximum ? n : maximum;
  13.             });
  14.             return (minimum, maximum);
  15.         }
  16.     }
  17. }

As per the above code snippet, the method returns a tuple which has two items. These items hold maximum and minimum values from number series.

Now, call this method from an executable program as per the following code snippet.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using static System.Console;
  5. namespace TupleApp
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             List<int> numbers = Enumerable.Range(1, 100).OrderBy(x => Guid.NewGuid()).Take(10).ToList();
  12.             Operation operation = new Operation();
  13.             (intint) data = operation.FindMinMax(numbers);
  14.             Write($“{data.Item1} is min and {data.Item2} is max from {String.Join(“,“, numbers)}”);
  15.             Read();
  16.         }
  17.     }
  18. }

As per the above code snippet, the method named FindMinMax calls and returns a tuple. When method directly returns more than one values into a Tuple type, it gives them some default name as per their order so as to call them easily. This tuple has two items so these items call Item1 and Item2. Item1 represents first value while Item2 represent second value. Tuple items are used in the same sequence which they are created in.

Now, run the application. The final result shows as in the below figure.

Figure 4 Output

As Item1 and Item2 don’t represent actual names of fields, so we can define custom names of them. Tuple type variables can have custom names instead of Item1 or Item2.

Let’s update the existing method named FindMinMax in the Operation class. We assign custom names to those tuple fields. The following code snippet is used for the same.

  1. using System.Collections.Generic;
  2. namespace TupleApp
  3. {
  4.     class Operation
  5.     {
  6.         internal (int Minimum, int Maximum) FindMinMax(List<int> list)
  7.         {
  8.             int maximum = int.MinValue, minimum = int.MaxValue;
  9.             list.ForEach(n =>
  10.             {
  11.                 minimum = n < minimum ? n : minimum;
  12.                 maximum = n > maximum ? n : maximum;
  13.             });
  14.             return (minimum, maximum);
  15.         }
  16.     }
  17. }

Here, the first field of the tuple has name Minimum while another field has name Maximum.

Now, call this method from an executable program as per the following code snippet.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using static System.Console;
  5. namespace TupleApp
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             List<int> numbers = Enumerable.Range(1, 100).OrderBy(x => Guid.NewGuid()).Take(10).ToList();
  12.             Operation operation = new Operation();
  13.             var data = operation.FindMinMax(numbers);
  14.             Write($“{data.Minimum} is min and {data.Maximum} is max from {String.Join(“,“, numbers)}”);
  15.             Read();
  16.         }
  17.     }
  18. }

The method named FindMinMax calls and returns a tuple. This tuple has two items that call Minimum and Maximum values as per the sequence of tuple items.

Now, run the application and see the result.

Figure 5 Output


Tuple is an ordered sequence of heterogeneous objects. It is used when a method is required to return more than one values.Tuple instance has a fixed number of items. Tuples have a limit of 8 items. If we want to create a Tuple with more items, we have to create nested Tuples. The eighth item of a Tuple should necessarily be another Tuple.

C# 7.0 Local Functions

We have been racing through the C#7 features in my latest series of posts; here is a list of what I have covered and what will be covered:

In today’s post, we will look at local functions. Those who are familiar with JavaScript will be familiar with local functions; the ability to define a method inside of another method. We have had a similar ability in C# since anonymous methods were introduced albeit in a slightly less flexible form. Up until C#7, methods defined within another method were assigned to variables and were limited in use and content. For example, one could not use yieldinside anonymous methods.

Local functions allow us to declare a method within the scope of another method; not as an assignment to a run-time variable as with anonymous methods and lambda expressions, but as a compile-time symbol to be referenced locally by its parent function. With lambda expressions, the compiler does some heavy lifting for us, creating an anonymous type to hold our method and its closures; also, to call them, a delegate must be instantiated and then invoked, which incurs additional memory overhead to standard method calls: none of this is necessary for local functions as they are regular methods. Not only that, but because these are regular methods, the full range of method syntax is available to us, including yield.

The official documentation provides a good overview of the differences between anonymous methods/lambda expressions and local functions, which ends with this paragraph:

While local functions may seem redundant to lambda expressions, they actually serve different purposes and have different uses. Local functions are more efficient for the case when you want to write a function that is called only from the context of another method.

The last sentence of that infers one of the most useful things about local methods; streaming enumerable sequences with fail early support. The yield syntax introduced in C#3 has been incredibly useful, simplifying the work necessary for defining an enumerator from writing an entire class to just writing a method. However, due to the way enumeration works, we often have to split our enumerator methods into two so that things like argument validation occur immediately, rather than when the first item in the sequence is requested, like this:

The NumbersImpl method is only ever used by the public-facing Numbers method, but we cannot make that any clearer. However, with C#7 and local functions, we can now embed that method declaration into the Numbers method and make our code explicit.

There are a couple of things to note here. First, we can declare the local function after it has been called; unlike anonymous methods and lambda expressions, local functions are just like any other method; they are part of the program declaration rather than its execution. Second, and somewhat surprisingly2, we can use closures.

Closures in Local Functions

With lambda expressions and anonymous methods, closures are hoisted into member variables of an anonymous type, but this is not how local functions work; local functions do not necessarily get their own anonymous type3. So how do closures work in local functions? Well, the compiler performs a little code-rewriting for us to effectively hoist the closures into method arguments so that we don’t have to repeat ourselves.

In Conclusion

Local functions provide a valuable alternative to anonymous methods and lambda expressions, and one-time use member functions. Not only do they make a clear distinction between run-time and compile-time, making the intent clear, but also by co-locating a single-use method with the code that calls it, we can make our code more readable. Of course, as with many other features of high-level languages like C#, this could be abused and make code horribly unreadable, so keep each other honest and be sure to call out incorrect or dubious usage when you see it.

You can read more about local functions in the official documentation.

What do you think? Will you use this new feature of C#? Does it make the language better? Please leave your views in the comments. Next week, we’ll take a look at some of the changes C#7 makes to returning values from our methods.

C# 7.0 – Pattern Matching

I already explained binary literalsdigit separatorstuplesout vars and ref returns, and expression bodied members – great new C# 7.0 features – in previous articles. Beside tuples, the biggest feature of C# 7.0 is pattern matching.

Pattern Matching

Often you need to work with the object type. It would be a lot easier to always use strongly typed interfaces and classes. However, this is not always the case. Also with interfaces and classes, sometimes you need to check for different interfaces or derived types to invoke other class members. The hierarchy of the types could be done differently to avoid such cases. However, often this is not practical, or a library used does not offer other ways features. Here, pattern matching can be applied.

C# 7.0 offers the first features for pattern matching: the is operator and the switch statement have been enhanced with the const pattern, the type pattern, and the var pattern.

Using the is Operator with Pattern Matching

The is operator is available since the first C# version. This operator can be used to check if an object is compatible with a specific type, e.g. if a specified interface is implemented, or if the type of the object derives from a base class. The result from this operator is true or false.

With the C# 7.0 extensions, the is operator can be used to check for patterns.

In the sample code, I’m creating an object array that consists of null, a number, and two Person objects. With every item of this list, the method IsPattern is invoked. This method demonstrates the pattern matching features of the isoperator.

object[] data = { null, 42, new Person("Matthias Nagel"), new Person("Katharina Nagel") };
foreach (var item in data)

Const Pattern

One available pattern with C# 7.0 is the const pattern. In the first sample I’m checking for null.

public static void IsPattern(object o)
    if (o is null) Console.WriteLine("it's a const pattern");

Without C# 7.0, you could do such checks using the == operator. Of course, you often checked for null throwing an ArgumentNullException. This code can now be changed to use the is operator instead.

public static void IsPattern(object o)
    if (o is null) throw new ArgumentNullException(nameof(o));

With a const pattern you can also verify for a const number, such as 42:

if (o is 42) Console.WriteLine("it's 42");

Type Pattern

With the type pattern, you can verify if the object is compatible with the specified type. What’s different to the syntax available before C# 7.0 is that if the pattern matches, the object is assigned to a new variable of the specified type.

if (o is int i) Console.WriteLine($"it's a type pattern with an int and the value {i}");

This is very practical, as you can strongly-typed access the members of the type, e.g. with the Person type:

if (o is Person p) Console.WriteLine($"it's a person: {p.FirstName}");

Not directly related to pattern matching, but of course you can also use logical operators to further reduce the matches:

if (o is Person p2 && p2.FirstName.StartsWith("Ka"))
    Console.WriteLine($"it's a person starting with Ka {p2.FirstName}");

Var Pattern

Using the var keyword for the type, this is the var pattern. This pattern always succeeds, as the object is always of a type. The advantage is that the variable declared with the var keyword is of the real type of the object, as you can see invoking the GetType method with the Name property.

if (o is var x) Console.WriteLine($"it's a var pattern with the type {x?.GetType()?.Name}");

In case o is null, invoking the GetType method on null throws a NullReferenceException. To avoid this exception, the null conditional operator is used that was introduced with C# 6.

Using the switch Statement with Pattern Matching

The switch statement has been enhanced as well. Using case, you can check for a const pattern (this was possible before), a type pattern to immediately declare a variable of the specified type, and the var pattern.

With the following code snippet pay special attention to the when keyword. You can enhance the pattern filter to only apply when a specific condition is fulfilled. Here, the when keyword is used – the same keyword already used with exception filters that are available since C# 6. With this you can define different cases for the same type. The first case that applies is taken.

public static void SwitchPattern(object o)
    switch (o)
        case null:
            Console.WriteLine("it's a constant pattern");
        case int i:
            Console.WriteLine("it's an int");
        case Person p when p.FirstName.StartsWith("Ka"):
            Console.WriteLine($"a Ka person {p.FirstName}");
        case Person p:
            Console.WriteLine($"any other person {p.FirstName}");
        case var x:
            Console.WriteLine($"it's a var pattern with the type {x?.GetType().Name} ");

Putting the generic catch for a Person before the catch with the specified when results in a compilation error. In such a scenario, the filtered catch would never apply because the generic one is taken first, and this results in the compiler error CS8120, “The switch case has already been handled by a previous case.”.


Pattern matching gives another C# 7.0 feature that can simplify and reduce your code with ideas from functional programmingis and switch/case have been enhanced to support consttype, and var patterns.

Pattern matching as it is implemented in C# 7.0 is just a begin for this feature. Sub-patterns, property patterns, positional patterns, and recursive patterns might be added to a future C# version.

Sample Code

The sample code is available at GitHub.

To run the sample code you need Visual Studio 2017 RC.

Have fun with programming and learning!

Inversion of Control, Dependency Injection and Service Locator in C#

Many developers get confused with the term Dependency Injection. mainly on: What is Dependency Injection ? Why is it required? what is the mechanism behind Dependency Injection ?
In this article we will discuss all these terms in simple words.

What is Dependency Inversion Principle (DIP)

The Dependency Inversion principle refers to a specific form of decoupling software modules.It states:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions

The Dependency Inversion principle (DIP) helps us to develop loosely couple code by ensuring that high-level modules depend on abstractions rather than concrete implementations of lower-level modules

What is Inversion Of Control (IOC)

Inversion of Control is a software design architecture where the framework controls the program flow. It means we are changing the control from normal way. IOC is used to increase modularity of the program and make it extensible.

To understand it better, lets look at an example.

When we are writing an ASP.net application, we are in ASP.net page life cycle but not in control where ASP.net is.

So as per the above diagram Dependency Injection (DI) and Service Locator (SL) are the ways of Implementing Inversion Of Control (IOC)

Difference between DIP and IOC (DIP VS IOC):

As stated earlier, DIP says high level module should not depend on low level module for abstraction and IOC provides abstraction.So if you want to make independent higher level module from the lower level module then you have to invert the control so that low level module will not control the interface and creation of the object.

Dependency Injection (DI):

  • Dependency Injection is a design pattern allows us to write loose coupled code
  • Dependency Injections helps us to manage future changes in code i.e. code maintainability
  • Dependency Injection uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to ‘inject’ a dependency from outside the class

Service Locator (SL):

  • Service Locator is a software design pattern that allows us to develop loosely coupled code.
  • It implements the DIP principle and easier to use with an existing codebase
  • It introduces a locator object that  is used to resolve dependencies within a class.

Difference between DI and SL (DI VS SL):

The Service Locator allows you to “resolve” a dependency within a class and the Dependency Injection allows you to “inject” a dependency from outside the class.

  1. When you use a service locator, every class will have a dependency on your service locator but in dependency injection,the dependency injector will typically be called only once at startup, to inject dependencies into the main class.
  2. The Service Locator pattern is easier to use in an existing codebase as it makes the overall design loosely coupled without forcing changes to the public interface. Code that is based on the Service Locator pattern is less readable than the equivalent code that is based on Dependency Injection.

Let’s look at an example:

The client class has a dependency on the Service class.

If you want to make it loosely coupled, you have to use IoC to make the more flexible and reusable it.

To implement the IoC, we have  two main patterns: Service Locator and Dependency Injection.

Service Locator Implementation:

Sample Service Locator Implementation:
The Inversion happens in the constructor, by locating the Service that implements the IService-Interface.

The dependencies are assembled by a “Locator”.

Dependency Injection Implementation:

Sample Builder Implementation:
The Injection happens in the constructor, by passing the Service that implements the IService-Interface.

The dependencies are assembled by a “Builder” and Builder responsibilities are as follows:

  • knowing the types of each IService
  • according to the request, send the abstract IService to the Client