What is Extension Methods?
Extension methods in C# are special static methods which allow you to add more functionalities (methods) to an existing type without modifying the original type.What Can You Extend
- Types
- Collections
- Interfaces
- Generic Classes and Interfaces
Creating Extension Methods
-
Create a public static class
public static class Sample { }
-
Add a public static method to the class you just created, make sure you add "this" keyword before the type of the first argument.
public static bool SampleMehtod(this string date) { return false; }
You have just successfully created an extension method by extending string type
As you can see, the visual studio gives intellisense for the extension methods and mark them with a downward arrow.
Create a new class library project with any valid name of your choice. In my own case, I name it DemoExtentionLib.
Add a folder with name ExtensionMehtods to the application root. Now add static class call SampleExtension with public access modifier as shown below:
Now, Let us add our extension methods to the class
Add a new Unit Test Project to the solution and name it DemoExtentionLibTest. Create a folder called ExtensionMehtodTest in the root of the Unit test project you just created. Add a new Unit test to this folder and rename it to SampleExtensionTest.
Your Project structure should look like:
Add DemoExtentionLib project reference to the DemoExtentionLibTest project and make sure you import the SampleExtension class namespace in the SampleExtensionTest class you just created.
Now let us add the Unit Test Method to test the extension methods we created.
Extension methods allow the developer to extend a code base in a clean and simplify way by adding methods. Note that you can only extend visible classes, properties, and method, although this limit can be bypassed using reflection it comes with performance penalties.
The complete source code can be downloaded here
Thank you, I hope it helps.
To use the extension method you just created
- Create a new class and add a method.
- Import the namespace of the extension method you created.
- Declare a variable as type string.
- On a new line type, the name of the variable follows by dot(.) and search for the name of the extension method you created on visual studio intellisence.
Note That:
- The extension method assembly must be properly referenced
- the namespace of the extension method must be imported
You can prevent importing extension method namespace by piggybacking namespace using system namespaces. This will make your extension methods available without importing any namespaces but this approach might overload visual studio intellisence with unnecessary content especially where they are not needed.
namespace System
{
public static class Sample
{
public static bool SampleMehtod(this string date)
{
return false;
}
}
}
A Walk Through Complete Sample Project
In this project, I will create extension methods that will check if a string value can be converted to some of C# primitive types (i.e int, double, decimal, DateTime, etc). I will also create a Unit test to validate these methods.Create a new class library project with any valid name of your choice. In my own case, I name it DemoExtentionLib.
Add a folder with name ExtensionMehtods to the application root. Now add static class call SampleExtension with public access modifier as shown below:
Now, Let us add our extension methods to the class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoExtentionLib.ExtensionMehtods
{
public static class SampleExtension
{
public static bool IsValidInteger(this string input)
{
int i;
return int.TryParse(input,out i);
}
public static bool IsValidDecimal(this string input)
{
decimal i;
return decimal.TryParse(input, out i);
}
public static bool IsValidDouble(this string input)
{
double i;
return double.TryParse(input, out i);
}
public static bool IsValidDate(this string input)
{
DateTime i;
return DateTime.TryParse(input, out i);
}
}
}
Add a new Unit Test Project to the solution and name it DemoExtentionLibTest. Create a folder called ExtensionMehtodTest in the root of the Unit test project you just created. Add a new Unit test to this folder and rename it to SampleExtensionTest.
Your Project structure should look like:
Add DemoExtentionLib project reference to the DemoExtentionLibTest project and make sure you import the SampleExtension class namespace in the SampleExtensionTest class you just created.
Now let us add the Unit Test Method to test the extension methods we created.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DemoExtentionLib.ExtensionMehtods;
namespace DemoExtentionLibTest.ExtensionMehtodTest
{
[TestClass]
public class SampleExtensionTest
{
[TestMethod]
public void SampleExtensionTestMehtod()
{
string input1 = "1000";
string input2 = "12.09";
string input3 = "04/25/2018";
Assert.Equals(true, input1.IsValidInteger());
Assert.Equals(true, input2.IsValidDouble());
Assert.Equals(true, input3.IsValidDate());
Assert.Equals(false, input3.IsValidInteger());
}
}
}
Right Click on the Test Method and Run Test, Our Unit test will be Passed.
Extension methods allow the developer to extend a code base in a clean and simplify way by adding methods. Note that you can only extend visible classes, properties, and method, although this limit can be bypassed using reflection it comes with performance penalties.
The complete source code can be downloaded here
Thank you, I hope it helps.
Using C# Extension Methods
Reviewed by Akintunde Toba
on
January 26, 2018
Rating:
No comments: