Saturday, October 26, 2024

Extension method and use it in C#

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. 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

Hot Topics