DEV Community

Renan Martins
Renan Martins

Posted on

How Extension Methods Unlock LINQ’s Magic in C#

LINQ feels like magic: you call .Where() on a list, and it just works. The secret? Extension methods.

What are Extension Methods?

They allow us to “add” methods to existing classes without modifying them.

To create one, you need:

  • A static class to contain your extensions.
  • A static method inside that class.
  • The this keyword before the first parameter tells the compiler which type you’re extending.
  • The namespace defines the scope, it'll apply just for the defined, to use in another using statement must be used.

Adding Behavior to Strings

public static class StringExtensions
{
    public static bool IsCapitalized(this string input)
    {
        if (string.IsNullOrEmpty(input)) return false;
        return char.IsUpper(input[0]);
    }
}

Console.WriteLine("Hello".IsCapitalized()); // True
Console.WriteLine("world".IsCapitalized()); // False
Enter fullscreen mode Exit fullscreen mode

This shows the basic idea: we added a new method to string, even though we don’t own the string class.


Making Collections Smarter with Generics

Extension methods get really useful when working with collections. Let’s make one that works with any type and mimics the idea of LINQ’s Where.

public static class EnumerableExtensions
{
    public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> source) where T : class
    {
        var result = new List<T>();
        foreach (var item in source)
        {
            if (item != null)
                result.Add(item);
        }
        return result;
    }
}

var names = new List<string?> { "Alice", null, "Bob", null, "Charlie" };
var filtered = names.WhereNotNull();
Console.WriteLine(string.Join(", ", filtered)); 
// Output: Alice, Bob, Charlie
Enter fullscreen mode Exit fullscreen mode

Here we combined generics (T) with IEnumerable<T>:

  • It works with any reference type.
  • It feels just like a LINQ method (WhereNotNull is similar to Where(x => x != null)).

Key Takeaways

  • Extension methods let you “teach” existing types new tricks.
  • They can be simple (string.IsCapitalized()) or collection-based (WhereNotNull<T>()).
  • Always remember: static class + static method + this keyword + correct namespace = extension method.
  • LINQ itself is just a big set of extension methods for IEnumerable<T>.

✅ That’s all, folks!

💬 Let’s Connect

Have any questions, suggestions for improvement, or just want to share your thoughts?

Feel free to leave a comment here, or get in touch with me directly on LinkedIn — I’d love to connect!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.