Extension Methods
Extension Methods are a powerful feature of C# that allow us to add new methods to an existing type without modifying its original source code or creating a derived class.
What is an Extension Method?
Suppose we have an existing class such as string or int. We may want to add our own functionality to that type.
Instead of changing the original class, C# allows us to create a static method that behaves like an instance method.
Extension Method Syntax
public static returnType MethodName(
this TypeName parameter)
{
// Method logic
}
The this keyword before the first parameter tells C# that the method is an extension method for that type.
Simple Extension Method Example
using System;
static class MyExtensions
{
public static void SayHello(this string name)
{
Console.WriteLine("WelCome CIIT " + name);
}
}
class Program
{
static void Main()
{
string name = "Institute 😍..";
name.SayHello();
}
}
Output
WelCome CIIT Institute 😍..
How Extension Methods Work
In the above example, SayHello() is not actually a method defined inside the string class.
The method is defined inside MyExtensions, but the this string name parameter allows us to call it using:
name.SayHello();
Extension Method for int
Extension methods can be created for built-in types such as int.
using System;
static class NumberExtensions
{
public static bool IsEven(this int number)
{
return number % 2 == 0;
}
}
class Program
{
static void Main()
{
int number = 10;
Console.WriteLine(number.IsEven());
}
}
Output
True
Extension Method for String
We can create custom string-related functionality using extension methods.
using System;
static class StringExtensions
{
public static int WordCount(this string text)
{
if (string.IsNullOrWhiteSpace(text))
{
return 0;
}
return text.Split(
' ',
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
class Program
{
static void Main()
{
string sentence = "C# is easy to learn";
Console.WriteLine(sentence.WordCount());
}
}
Output
5
Extension Method with Additional Parameters
An extension method can also accept additional parameters after the first parameter marked with this.
using System;
static class NumberExtensions
{
public static int Add(
this int number,
int value)
{
return number + value;
}
}
class Program
{
static void Main()
{
int number = 10;
Console.WriteLine(number.Add(5));
}
}
Output
15
Extension Method for Collections
Extension methods are frequently used with collections and are an important part of the .NET and LINQ programming model.
using System;
static class ListExtensions
{
public static int CountEven(
this List<int> numbers)
{
return numbers.Count(
number => number % 2 == 0);
}
}
class Program
{
static void Main()
{
List<int> numbers =
new List<int> { 10, 15, 20, 25, 30 };
Console.WriteLine(
numbers.CountEven());
}
}
Output
3
Multiple Extension Methods
A static extension class can contain multiple extension methods for the same or different types.
using System;
static class StringExtensions
{
public static bool IsLong(
this string text)
{
return text.Length > 10;
}
public static string MakeUpper(
this string text)
{
return text.ToUpper();
}
}
class Program
{
static void Main()
{
string text = "WelCome to CIIT Training Institute 👨🏫❤️...!";
Console.WriteLine(text.IsLong());
Console.WriteLine(text.MakeUpper());
}
}
Output
True
WelCome to CIIT Training Institute 👨🏫❤️...!
Calling Extension Method as a Static Method
Although extension methods are normally called using instance syntax, they can also be called like normal static methods.
string name = "Sam";
name.SayHello();
The compiler treats this approximately like:
MyExtensions.SayHello(name);
Rules for Extension Methods
- The extension method must be declared inside a static class.
- The extension method itself must be static.
- The first parameter must use the this keyword.
- The first parameter specifies the type being extended.
- The extension class must be accessible where the method is used.
- A namespace import may be required to bring the extension method into scope.
Advantages of Extension Methods
- Allows adding functionality without modifying existing classes.
- Makes utility functionality easier to discover and use.
- Can improve code readability.
- Works with classes, structures, interfaces, and other types.
- Widely used throughout .NET libraries.
- Very useful when creating reusable helper functionality.
Limitations of Extension Methods
- Extension methods cannot access private members of the extended type.
- They do not actually modify the original type.
- Too many extension methods can make APIs difficult to understand.
- They should be used when they make the code clearer.
Extension Method vs Normal Method
| Feature | Normal Method | Extension Method |
|---|---|---|
| Defined inside | Class itself | Separate static class |
| Requires this | No | Yes, for first parameter |
| Modifies original class | Yes | No |
| Calling style | object.Method() | object.ExtensionMethod() |
Extension Methods and LINQ
Many LINQ methods are implemented as extension methods. This is why we can write methods such as Where(), Select(), OrderBy(), and Count() directly on collections.
using System;
List<int> numbers =
new List<int> { 10, 20, 30, 40, 50 };
var result =
numbers.Where(number => number > 20);
foreach (int number in result)
{
Console.WriteLine(number);
}
Output
30
40
50
Example 📩🌍
In an enterprise application, developers often create reusable extension methods for formatting, validation, conversion, logging helpers, or common business operations.
using System;
static class ValidationExtensions
{
public static bool IsValidEmail(
this string email)
{
return email.Contains("#");
}
}
class Program
{
static void Main()
{
string email = "student@example.com";
Console.WriteLine(
email.IsValidEmail());
}
}
Output
False
Common Mistakes
- Forgetting to make the extension class static.
- Forgetting to make the extension method static.
- Forgetting the this keyword.
- Using an incorrect first parameter type.
- Creating too many unnecessary extension methods.
- Trying to access private members of the extended type.
- Forgetting the namespace containing the extension method.
Interview Questions
1. What is an Extension Method?
An Extension Method allows us to add functionality to an existing type without modifying its source code.
2. Where are Extension Methods declared?
Extension methods are declared inside a static class.
3. Why is the this keyword used?
The this keyword on the first parameter identifies the type that the extension method extends.
4. Can an Extension Method access private members?
No. Extension methods do not have special access to private members of the extended type.
5. Are LINQ methods Extension Methods?
Many LINQ methods are implemented as extension methods, allowing them to be called directly on collections.
Summary
Extension Methods allow developers to add new functionality to existing types without changing their original source code.
You learned how to create extension methods using a static class, the static keyword, and the this keyword.
Extension methods can be created for strings, integers, collections, and custom types. They are also heavily used by the .NET framework and LINQ.
Understanding Extension Methods helps developers write reusable, readable, and maintainable C# and .NET applications.
Practice Questions
- Create an extension method for string to convert text to uppercase.
- Create an extension method for int to check whether a number is even.
- Create an extension method to calculate the square of a number.
- Create an extension method to count words in a string.
- Create an extension method for a List of integers.
- Create an extension method that checks whether an email is valid.
- Create multiple extension methods inside one static class.
- Explain the purpose of the this keyword in extension methods.
- Explain the difference between normal methods and extension methods.
- Explain how LINQ uses extension methods.