Let’s go through extension methods in C# β€” a way to add new methods to existing types without modifying them.


πŸ“Œ 1. What Are Extension Methods?

  • An extension method allows you to β€œextend” an existing class or interface with a new method.

  • Useful for adding functionality to built-in types or third-party classes.

  • Declared as static methods in a static class.


πŸ“Œ 2. Basic Syntax

public static class StringExtensions
{
    public static bool IsCapitalized(this string str)
    {
        if (string.IsNullOrEmpty(str)) return false;
        return char.IsUpper(str[0]);
    }
}
  • this string str β†’ indicates extension for the string type

  • Can now call .IsCapitalized() on any string


πŸ“Œ 3. Using Extension Methods

string name = "Alice";
bool result = name.IsCapitalized();
Console.WriteLine(result); // True
  • Looks like a normal method of the class, but it’s defined externally

πŸ“Œ 4. Extension Methods with Parameters

public static class IntExtensions
{
    public static bool IsDivisibleBy(this int number, int divisor)
    {
        return number % divisor == 0;
    }
}
 
int num = 10;
Console.WriteLine(num.IsDivisibleBy(5)); // True
Console.WriteLine(num.IsDivisibleBy(3)); // False
  • Extension methods can take additional parameters just like regular methods

πŸ“Œ 5. Extension Methods with LINQ

  • LINQ uses extension methods extensively

  • Example: Where(), Select(), OrderBy() are all extension methods for IEnumerable<T>

int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0); // LINQ extension

πŸ“Œ 6. Rules for Extension Methods

  1. Must be declared in a static class

  2. Must be static method

  3. First parameter specifies the type being extended with this

  4. Cannot override existing instance methods


πŸ“Œ 7. Advantages

  • Add methods to existing classes without inheritance or modifying original code

  • Makes code more readable and fluent

  • Essential for fluent interfaces and LINQ operations


πŸ“Œ 8. Summary Table

FeatureDescription
Declarationpublic static class, public static method
this keywordMarks the type being extended
UsageCall as if it’s an instance method
BenefitsAdds functionality without modifying original class, improves readability
Common Use CaseLINQ methods, helper methods for built-in types

βœ… Tip:

  • Use extension methods to add small helper functions to classes you cannot modify

  • Avoid adding too many unrelated methods to keep the API clean