An extension method has simplified calling syntax. It represents a static
method as an instance method. Extension methods can lead to simpler syntax.
An extension method uses the this
-keyword in its parameter list. It must be located in a static
class
. We often use special "Extensions" classes.
Here is a custom extension method. Usually you will want to store your extension method class
in a separate source file (like ExtensionMethods.cs
) in the project.
static
class
with public static
extension methods.static
and can be public so you can use it anywhere in your source code.this
-keyword before the appropriate parameter you want the method to be called upon.using System; public static class ExtensionMethods { public static string UppercaseFirstLetter(this string value) { // Uppercase the first letter in the string. if (value.Length > 0) { char[] array = value.ToCharArray(); array[0] = char.ToUpper(array[0]); return new string(array); } return value; } } class Program { static void Main() { // Use the string extension method on this value. string value = "dot net perls"; value = value.UppercaseFirstLetter(); Console.WriteLine(value); } }Dot net perls
Here is an extension method that acts on ints. It receives a parameter—the multiplier for the operand. It returns another int
so can be used in function call chains.
using System; static class Extensions { public static int MultiplyBy(this int value, int multiplier) { // Uses a second parameter after the instance parameter. return value * multiplier; } } class Program { static void Main() { // Ten times 2 is 20. // Twenty times 2 is 40. int result = 10.MultiplyBy(2).MultiplyBy(2); Console.WriteLine(result); } }40
The only difference in the declaration between a regular static
method and an extension method is the "this" keyword in the parameter list.
There are many extension methods available. These extension methods were written by Microsoft developers and are available in all C# programs targeting recent .NET Framework versions.
System.Linq
" directive to the top of the code.Extension methods can have many arguments. We can use variable "params
" arguments with extension methods. Extension methods are static
methods—so there is no performance loss.
You can add extension methods to any type, even a value type. The original representation of the type does not change. Extension methods affect syntax, not execution.