Objectives:
- What is Extension Method
- How to create Extension methods
- How to use Extension Method
Extension methods in C# allow you to add new methods to existing types without modifying the original type or creating a new derived type.
Features of Extension Method
- It is defined as a member of static class.
- It is a static method which first parameter's type is the type which extension method is being defined; also this first parameter must be prefixed/qualified with this keyword.
- It is invoked or called on the instance of the type (as if the this static method is an extension method of the type).
Here's how you can create and use extension methods in C#:
1. Create a static class for extension methods: First, create a static class to contain the extension methods. The class should be static, and the methods should also be static. The class should be in the same namespace as the types you want to extend.
using System;
public static class StringExtensions
{
public static string Reverse(this string str)
{
char[] charArray = str.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
In this example, we're creating an extension method called Reverse for the string type.
2. Define the extension method: The extension method is a static method defined in the static class. It takes the type to be extended as the first parameter, prefixed with the this keyword.
3. Using the extension method: You can then use the extension method on instances of the extended type.
using System;
class Program
{
static void Main(string[] args)
{
string originalString = "hello";
string reversedString = originalString.Reverse();
Console.WriteLine("Original: " + originalString);
Console.WriteLine("Reversed: " + reversedString);
}
}
In this example, we're calling the Reverse extension method on a string instance.
4. Output: The Reverse extension method modifies the behavior of the string type without modifying the original string class.
Original: hello
Reversed: olleh
Remember to include the namespace where the extension method class is defined (if it's in a different namespace) or import the namespace to use the extension methods.
No comments:
Post a Comment