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″);

Output

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:

Output:

black
red
white

Description:

  • 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:

Output:

black red white black red white

Description:

  • 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

Output:

Iterators as Properties:

Output:

Description:

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.

Summary:

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.

Solution

  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.

Summary:

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

Conclusion

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.

1
2
3
4
5
6
object[] data = { null, 42, new Person("Matthias Nagel"), new Person("Katharina Nagel") };
foreach (var item in data)
{
    IsPattern(item);
}

Const Pattern

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

1
2
3
4
5
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.

1
2
3
4
5
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:

1
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.

1
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:

1
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:

1
2
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.

1
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void SwitchPattern(object o)
{
    switch (o)
    {
        case null:
            Console.WriteLine("it's a constant pattern");
            break;
        case int i:
            Console.WriteLine("it's an int");
            break;
        case Person p when p.FirstName.StartsWith("Ka"):
            Console.WriteLine($"a Ka person {p.FirstName}");
            break;
        case Person p:
            Console.WriteLine($"any other person {p.FirstName}");
            break;
        case var x:
            Console.WriteLine($"it's a var pattern with the type {x?.GetType().Name} ");
            break;
        default:
            break;
    }
}

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.”.

Summary

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!
Christian

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

singleton design pattern c#

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance – as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily – i.e. that the instance isn’t created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing – if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn’t known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.

First version – not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
private static Singleton instance=null;private Singleton()
{
}

public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn’t guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version – simple thread-safety

public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();Singleton()
{
}

public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time – by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine – wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version – attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();Singleton()
{
}

public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn’t work in Java. This may seem an odd thing to comment on, but it’s worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn’t ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it’s broken in the ECMA CLI specification too. It’s possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it’s safe, but I’d rather not rely on those stronger semantics, especially if there’s any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can’t agree exactly which barriers are required. I tend to try to avoid situations where experts don’t agree what’s right and what’s wrong!
  • It’s easy to get wrong. The pattern needs to be pretty much exactly as above – any significant changes are likely to impact either performance or correctness.
  • It still doesn’t perform as well as the later implementations.

Fourth version – not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}

private Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

As you can see, this is really is extremely simple – but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

  • It’s not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers – they’re unlikely to bite you, but it’s worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn’t marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don’t have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have an article with more details about this issue. Also note that it affects performance, as discussed near the bottom of the page.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version – fully lazy instantiation

public sealed class Singleton
{
private Singleton()
{
}public static Singleton Instance { get { return Nested.instance; } }

private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class’s private members, the reverse is not true, hence the need for instance to be internal here. That doesn’t raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Sixth version – using .NET 4’s Lazy<T> type

If you’re using .NET 4 (or higher), you can use the System.Lazy<T> type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor – which is done most easily with a lambda expression.

public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());public static Singleton Instance { get { return lazy.Value; } }

private Singleton()
{
}
}

It’s simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.

Performance vs laziness

In many cases, you won’t actually require full laziness – unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it’s probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class.

A lot of the reason for this page’s existence is people trying to be clever, and thus coming up with the double-checked locking algorithm. There is an attitude of locking being expensive which is common and misguided. I’ve written a very quick benchmark which just acquires singleton instances in a loop a billion ways, trying different variants. It’s not terribly scientific, because in real life you may want to know how fast it is if each iteration actually involved a call into a method fetching the singleton, etc. However, it does show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to acquire the singleton a billion times in under 40 seconds. (Note: this article was originally written quite a while ago now – I’d expect better performance now.) That means that if you’re “only” acquiring the singleton four hundred thousand times per second, the cost of the acquisition is going to be 1% of the performance – so improving it isn’t going to do a lot. Now, if you are acquiring the singleton that often – isn’t it likely you’re using it within a loop? If you care that much about improving the performance a little bit, why not declare a local variable outside the loop, acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily adequate.

I would be very interested to see a real world application where the difference between using simple locking and using one of the faster solutions actually made a significant performance difference.

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don’t know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I’d suggest using the second pattern listed on the page – just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn’t already been successfully built.

Thanks to Andriy Tereshchenko for raising this issue.

C# and its Features

  1. C# is a simple, modern, object oriented language derived from C++ and Java. 
  2. It aims to combine the high productivity of Visual Basic and the raw power of C++. 
  3. It is a part of Microsoft Visual Studio 7.0. 
  4. Visual Studio supports VB, VC++, C++, VBscript, JScript. All of these languages provide access to the Microsft .NET platform.
  5. .NET includes a Common Execution engine and a rich class library.
  6. Microsofts JVM eqiv is Common language run time(CLR).
  7. CLR accommadates more than one languages such as C#, VB.NET, Jscript, ASP.NET,C ++.
  8. Source code —>Intermediate Language code(IL) —> (JIT Compiler) Native code.
  9. The classes and data types are common to all of the .NET languages.
  10. We may develop Console application, Windows application, and Web application using C#.
  11. In C#, Microsoft has taken care of C++ problems, such as Memory management, pointers etc.
  12. It supports garbage collection, automatic memory management, and a lot.

MAIN FEATURES OF C#

1. SIMPLE

  1. Pointers are missing in C#.
  2. Unsafe operations such as direct memory manipulation are not allowed.
  3. In C# there is  no usage of “::” or “->” operators.
  4. Since it’s on .NET, it inherits the features of automatic memory management and garbage collection.
  5. Varying ranges of the primitive types like Integer,Floats etc.
  6. Integer values  of 0 and 1 are no longer accepted as boolean values.Boolean values are pure true or false values in C# so no more errors of “=”operator and “==”operator.
  7. “==” is used for comparison operation and “=” is used for assignment operation.

2. MODERN

 

  • C# has been based according to the current trend and is very powerful and simple for building interoperable, scable, robust applications.
  • C# includes built in support to turn any component into a web service that can be invoked over the internet from any application running on any platform.

 

3. OBJECT ORIENTED

  1. C# supports Data Encapsulation, inheritance,polymorphism, interfaces.
  2. (int,float, double) are not objects in java but C# has introduces structures(structs) which enable the primitive types to become objects.int i=1;
    string a=i Tostring(); //conversion (or) Boxing

4. TYPE SAFE

 

  • In C# we cannot perform unsafe casts like convert double to a boolean.
  • Value types (priitive types) are initialized to zeros and reference types (objects and classes) are initialized to null by the compiler automatically.
  • arrays are zero base indexed and are bound checked.
  • Overflow of types can be checked.

 

5. INTEROPERABILITY

  1. C# includes native support for the COM and windows based applications.
  2. Allowing restriced use of native pointers.
  3. Users no longer have to explicityly implement the unknown and other COM interfacers, those features are built in.
  4. C# allows the users to use pointers as unsafe code blocks to manipulate your old code.
  5. Components from VB NET and other managed code languages and directlyt be used in C#.

6. SCALABLE AND UPDATEABLE

 

  • .NET has introduced assemblies which are self describing by means of their manifest. manifest establishes the assembly identity, version, culture and digital signature etc. Assemblies need not to be register anywhere.
  • To scale our application we delete the old files and updating them with new ones. No registering of dynamic linking library.
  • Updating software components is an error prone task. Revisions made to the code. can effect the existing program C# support versioning in the language. Native support for interfaces and method overriding enable complex frame works to be developed and evolved over time.

 

CONCLUSION

C# is a modern, type safe programming language, object oriented language that enables programmers to quickly and easily build solutions for the Microsoft .NET platform.