C# Extension methods : How to Add new method without modifying the original type ?




If you are using Visual Studio so you know about intellisense. It gives all possible suggestion for coding. you may also know about icons before suggestions or icon categories in the bottom.

You may also know about Method Icon 
but you ever notice about this icon 
This icon is also used for Method but it is used to display special kind of method which is known as the extension method.





What is an extension method?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

This is the definition ,I copied from https://docs.microsoft.com. but the definition is not enough.

So let's create one.

Create New Console or Win or any project in c#. Then create Person Class :

  public class Person  
   {  
     public string FirstName { get; set; }  
     public string MiddleName { get; set; }  
     public string LastName { get; set; }  
     //  
     // Summary:  
     //   this is simple method within a class, which is return full name without Middle Name  
     //  
     public string getFullName()  
     {  
       return FirstName + " " + LastName;  
     }  
   }  

Create Person object and call getFullName method and let's see the output.


Output :



Ohh no, this method return full name without full name, so let's create an extension method which is return full name with a middle name.

Create static class PersonEx and create static method getEntireName.


  public static class PersonEx  
   {  
     //this is extension method which get person object as an argument   
     public static string getEntireName(this Person person)  
     {  
       return person.FirstName + " " + person.MiddleName + " " + person.LastName;  
     }  
   }  

don't forget to write this before argument.



Output :


Ooooyaaaaa.

(note: If you writing extension method in other namespaces which is normal please import namespace of extension class)


it ( try , code , like , comment , share)

Comments