Extension Methods in C#



In C#, Extension Methods let you add new methods to an existing class or interface without changing its source code.

Extension Methods in C#

An extension method in C# is a special kind of static method of static class that can be called as if it were an instance method on the type it extends.

Extension methods are available only when you import their namespace using a using directive.

Here are some of the key points regarding extension methods −

  • Extension methods are defined in a static class.
  • The first parameter starts with the "this" keyword, followed by the type you want to extend.
  • You cannot override existing methods with extension methods.
  • Extension methods are often used to add helper or utility methods.

How to Declare an Extension Method

Use the following syntax to declare an extension method in C#

public static class ClassName{
   public static returnType MethodName(this TypeToExtend obj, parameters) {
      // method's body
   }
}

Let's understand this by a C# example, where we are adding a method to the "string" class −

using System;
public static class StringExtensions {
   // Extension Method to count words in a string
   public static int WordCount(this string str){
      if (string.IsNullOrEmpty(str))
         return 0;
      return str.Split(' ').Length;
   }
}

class Program {
   static void Main(){
      string message = "C# makes coding easier";
      // calling extension method
      int count = message.WordCount();
      Console.WriteLine("Word Count: " + count);
   }
}

When you run this code, it will produce the following output

Word Count: 4

Types of Extension Methods in C#

Basically extension method are divided into three types

  • Extension Method on Built-in Type
  • Extension Method on User-defined Class
  • Extension Method on Interface

Let's now understand each of these extension methods in detail.

Extension Method on Built-in Type

In this type of extension method, we can add new methods to built-in types like string, int, double, etc., without modifying their original definition.

Take a look at the following example. Here, we added a new method, IsEven(), to the built-in int type. Therefore, any integer can call .IsEven() as if it were a normal method.

using System;
public static class IntExtensions {
   // Extension method for int type
   public static bool IsEven(this int number){
      return number % 2 == 0;
   }
}

class Program {
   static void Main(){
      int num = 10;
      // Output: True
      Console.WriteLine(num.IsEven());
   }
}

Following is the output

True

Extension Method on User-defined Class

An extension method on a user-defined class can help you create an extension method for your own classes to add extra functionality without modifying the class directly.

In the following example, observe that DisplayWelcome() is an extension method that adds a new behaviour to the Student class without changing the original class code.

using System;

public class Student {
   public string Name { get; set; }
}

public static class StudentExtensions {
   // Extension method for Student class
   public static void DisplayWelcome(this Student s){
      Console.WriteLine($"Welcome, {s.Name}!");
   }
}

class Program {
   static void Main() {
      Student stu = new Student { Name = "Aman" };
      stu.DisplayWelcome();
   }
}

Following is the output

Welcome, Aman!

Extension Method on Interface

In this type, we can define extension methods for interfaces, which means all those classes that implement a given interface can use the extension method.

Take a look a the following example. Here, the extension method Eat() is defined for the IAnimal interface. Since Dog implements IAnimal, it automatically gets access to the Eat() method.

using System;
public interface IAnimal {
   void Speak();
}

public class Dog : IAnimal {
   public void Speak() => Console.WriteLine("Woof!");
}

public static class AnimalExtensions {
   // Extension method for IAnimal interface
   public static void Eat(this IAnimal animal) {
      Console.WriteLine("Animal is eating...");
   }
}

class Program {
   static void Main() {
      IAnimal dog = new Dog();
      dog.Speak();
      dog.Eat();
   }
}

Run the code and check its output

Woof!
Animal is eating...

Benefits of Using Extension Methods

Following are the benefits of using extension methods in C#

  • Non-intrusive − Extension methods add functionality without modifying the class.
  • Readable syntax − Extension methods help make the code look clean and organized because we call them like instance methods, not static methods. We can group related logic in static helper classes.
  • Reusable − Once defined, extension methods can be used in multiple projects easily.
  • Extends interfaces− Extension methods can be added to interfaces, allowing all implementing classes to share new functionality without changing their definitions.

Conclusion

Extension methods in C# make our C# codes clearer, more readable, and more flexible; we can use them anywhere in C# projects. Extension methods are a great way to extend existing types without inheritance or modification.

Advertisements