C# extension methods allow you to add new functionality to existing types without modifying their original source code. They are a powerful feature in C# that allow you to extend classes, interfaces, and structs, even those defined in .NET framework or third-party libraries.
To define an extension method, you need to create a static class and define static methods within that class. Here’s the general syntax for declaring an extension method:
public static class ExtensionClassName { public static ReturnType ExtensionMethodName(this ExtendedType extendedObject, parameters) { // Method implementation } }
Let’s break down the parts of the extension method declaration:
public static class ExtensionClassName
: This is a static class that contains the extension methods. It must be declared aspublic
andstatic
.public static ReturnType ExtensionMethodName(this ExtendedType extendedObject, parameters)
: This is the extension method itself. It should be declared aspublic
,static
, and should have a return type (ReturnType
). The first parameter (this ExtendedType extendedObject
) is the object being extended, and it is preceded by thethis
keyword. The following parameters are optional and depend on your specific needs.
Once you’ve defined an extension method, you can use it as if it were an instance method on the extended type. Here’s an example:
public static class StringExtensions { public static string Reverse(this string str) { char[] charArray = str.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } }
In the example above, we define an extension method called Reverse
for the string
type. It reverses the characters in a string and returns the result.
Now, you can use the extension method as follows:
string myString = "Hello, World!"; string reversedString = myString.Reverse(); // Using the extension method Console.WriteLine(reversedString); // Output: "!dlroW ,olleH"
Extension methods can be very useful for adding utility functions, providing syntactic sugar, or enhancing the capabilities of existing types in your codebase without modifying their original implementation.
C# Extension Methods Example:
Certainly! Here’s an example of a C# extension method:
Let’s say we want to add an extension method to the IEnumerable<T>
interface to calculate the sum of all elements in a collection. Here’s how we can do it:
using System; using System.Collections.Generic; public static class EnumerableExtensions { public static int Sum(this IEnumerable<int> collection) { int sum = 0; foreach (int item in collection) { sum += item; } return sum; } }
In the example above, we define an extension method called Sum
for the IEnumerable<int>
interface. It calculates the sum of all elements in the collection by iterating through each element and adding it to the sum
variable.
Now, let’s use the extension method on a collection of integers:
using System; using System.Collections.Generic; public class Program { public static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; int sum = numbers.Sum(); // Using the extension method Console.WriteLine(sum); // Output: 15 } }
In the above example, we create a List<int>
containing the numbers 1 to 5. Then, we use the Sum
extension method on the numbers
collection to calculate the sum of all elements. The result, 15, is then printed to the console.
Extension methods provide a way to extend the functionality of existing types, making your code more expressive and reusable.