Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or modifying the original type. Declared as static methods using this.
C# Extension Methods
Add new methods to existing types without modifying original source code.
Key Takeaways: C# Extension Methods
Mastering C# Extension Methods helps you write clean and reliable C# code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C# Extension Methods Code Example
C#using System;
public static class StringExtensions {
public static int WordCount(this string str) {
return str.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
}
}
class Program {
static void Main() {
string text = "CodesInTech Software Consultancy";
Console.WriteLine($"Word count: {text.WordCount()}");
}
}
Output
Word count: 3
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services