Wednesday, 23 January 2019

Extension method with example

What are extension methods?


Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. 

An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.

How to use extension methods?


An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Program to show how to use extension methods


Create a project Class Library as:

extMetLib.gif
  1. using System;  
  2. using System.Text;  
  3.   
  4. namespace ClassLibExtMethod  
  5. {  
  6.     public class Class1  
  7.     {  
  8.         public string Display()  
  9.         {  
  10.             return ("I m in Display");  
  11.         }  
  12.   
  13.         public string Print()  
  14.         {  
  15.             return ("I m in Print");  
  16.         }  
  17.     }  
  18. }  
Now create a new project using "File" -> "New" -> "Project...".

extMetProject.gif

Add the reference of the previously created class library to this project.

addRefLib.gif

Use the following code and use the ClassLibExtMEthod.dll in your namespace:
  1. using System;  
  2. using System.Text;  
  3. using ClassLibExtMethod;  
  4.   
  5. namespace ExtensionMethod1  
  6. {  
  7.     public static class XX  
  8.     {  
  9.          public static void NewMethod(this Class1 ob)  
  10.         {  
  11.             Console.WriteLine("Hello I m extended method");  
  12.         }  
  13.     }  
  14.   
  15.     class Program  
  16.     {  
  17.         static void Main(string[] args)  
  18.         {  
  19.             Class1 ob = new Class1();  
  20.             ob.Display();  
  21.             ob.Print();  
  22.             ob.NewMethod();  
  23.             Console.ReadKey();  
  24.         }  
  25.     }  
  26. }  
You can see the extension method with an arrow (different from the normal method sign), since they were instance methods on the extended type. See the figure below:

extensionMethod.gif

Output of the preceding program

extensionMethod1.gif

Benefits of extension methods

  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
  • If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods.
  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design.

Generics and Collections with example


Generics provides the type safe code with re-usability like as algorithm. In algorithms such as sorting, searching, comparing etc. you don’t specify what data type(s) the algorithm operates on. The algorithm can be operates with any types of data. In the same way Generics operate, you can provide different data type to Generics. For example, a sorting algorithm can operates on integer type, decimal type, string type, DateTime type etc.
In this article, I will demonstrate the advantage of Generics over Collections. Following are the main advantage of Generics.

Code Re-usability with Generics

Suppose, you required to sort the integer and floating type numbers, then let's see how to do in collections and generics.

How to do it using Collections

  1. //Overloaded sort methods
  2. private int[] Sort(int[] inputArray)
  3. {
  4. //Sort array
  5. //and return sorted array
  6. return inputArray;
  7. }
  8. private float[] Sort(float[] inputArray)
  9. {
  10. //Sort array
  11. //and return sorted array
  12. return inputArray;
  13. }

How to do it using Generics

  1. private T[] Sort(T[] inputArray)
  2. {
  3. //Sort array
  4. //and return sorted array
  5. return inputArray;
  6. }
Here, T is short for Type and can be replaced with the Type defined in the C# language at runtime. So once we have this method, we can call it with different data types as follows and can see the beauty of Generics. In this way Generics provide code re-usability.
 
Now if you thinking you can make fool to the compiler by passing an integer array while it is asking for a float, you are wrong. Compiler will shows the error at compile time like as:

Type Safety with Generics

Suppose, you want to make a list of students, then let's see how to do in collections and generics.

How to do it using Collections

In collections we can use ArrayList to store a list of Student objects like as:
  1. class Student
  2. {
  3. public int RollNo{get; set;}
  4. public string Name{get; set;}
  5. }
  6.  
  7. //List of students
  8. ArrayList studentList = new ArrayList();
  9. Student objStudent = new Student();
  10. objStudent.Name = "Rajat";
  11. objStudent.RollNo = 1;
  12.  
  13. studentList.Add(objStudent);
  14.  
  15. objStudent = new Student();
  16. objStudent.Name = "Sam";
  17. objStudent.RollNo = 2;
  18.  
  19. studentList.Add(objStudent);
  20.  
  21. foreach (Object s in studentList)
  22. {
  23. //Type-casting. If s is anything other than a student
  24. Student currentStudent = (Student)s;
  25. Console.WriteLine("Roll # " + currentStudent.RollNo + " " + currentStudent.Name);
  26. }

Problem with Collections

Suppose by mistake you have added a string value to ArrayList like as
  1. studentList.Add("Generics"); //Fooling the compiler
Since ArrayList is a loosely typed collection and it never ensure compile-time type checking. Hence above statement will compile without error but it will throw an InvalidCastException at run time when you try to cast it to Student Type.

How to do it using Generics

In generics we can use generic List to store a list of Student objects like as:
  1. List<Student> lstStudents = new List<Student>();
  2.  
  3. Student objStudent = new Student();
  4. objStudent.Name = "Rajat";
  5. objStudent.RollNo = 1;
  6.  
  7. lstStudents.Add(objStudent);
  8.  
  9. objStudent = new Student();
  10. objStudent.Name = "Sam";
  11. objStudent.RollNo = 2;
  12.  
  13. lstStudents.Add(objStudent);
  14.  
  15. //Looping through the list of students
  16. foreach (Student currentSt in lstStudents)
  17. {
  18. //no need to type cast since compiler already knows that everything inside
  19. //this list is a Student
  20. Console.WriteLine("Roll # " + currentSt.RollNo + " " + currentSt.Name);
  21. }

Advantage with Generics

In case of collections you can make fool to compiler but in case of generics you can't make fool to compiler as shown below. Hence Generics provide Type Safety.

Cleaner Code with Generics

Since compiler enforces type safety with Generics. Hence fetching data from Generics doesn't required type casting which means your code is clean and easier to write and maintain.

Better Performance with Generics

As you have seen in above example, at the time of fetching the data from the ArrayList collection we need to do type casting which cause performance degrades. But at the time of fetching the data from the generic List we don't required to do type casting. In this way Generics provide better performance than collections.