Do you wish to extend the built-in types with new methods?
Want to extend custom types with new methods?
In C#, we can use the Extension Methods to extend both built-in types and custom types. These extension methods are introduced in C# 3.0
What are Extension Methods?
Extension methods are special kind of static methods in a static class which enables us to add new methods to built-in types and custom types without creating new derived type.
How to implement Extension Methods:
- Create a static method in a static class
- Pass the type which you want to extend, as a first parameter to method
- The first parameter should have the combination with keyword ‘this’ and ‘type’
The typical example of extension method looks like:
//Extending integer type public static int GetSumOfX(this int i) |
In the above example, keyword ‘this’ determines to which type the extension method belongs. And ‘this’ keyword is must be a first parameter to extension method.
In the above example you can find ‘int’ type is extended with one more new method ‘GetSumOfX’. Similarly you can extend custom types too.
Microsoft has implemented many extension methods which are integrated as part of .NET Framework. One of the best known example for this, using IEnumerable objects. When you are working with LINQ objects, these objects has the build in methods called First<>, FirstOrDefault<>, GroupBy<>, OrderBy<>, etc. All these are the extension methods of IEnumerable object.
In the below sample codes, you can find out extending both built-in types and custom types:
public static class MyExtensions public static int GetSumOfX(this int i) //Extending string type public static int GetTotalWords(this string s) //Extending Employee type public static string GetFullName(this Employee e) public class Employee public string GetLastName()
//Page_Load//Form_Load int num = 100;
string sentence = “This is a string data type”;
Employee emp = new Employee(); string fullName = emp.GetFullName(); //returns firstName+lastName |
In the above sample code, int type is extended with a new method to get the sum of N numbers and string type is extended with a new method to get number of words in a string. And also a custom type called Employee class is extended with a new method to get full name of employee.
Hope this helps you understanding extension methods in C#.