How to Create Extension Method in C# - Simple Guide
In C#, create an extension method by defining a static method inside a static class with the first parameter preceded by
this keyword to specify the type it extends. This allows you to call the method as if it were part of the original type.Syntax
An extension method must be a static method inside a static class. The first parameter uses the this keyword followed by the type you want to extend. This tells C# which type the method extends.
static class: container for extension methodsstatic method: the extension method itselfthis TypeName param: the type being extended
csharp
public static class ExtensionClass { public static ReturnType MethodName(this TypeName param, OtherParameters) { // method body } }
Example
This example adds an extension method IsEven to the int type. It returns true if the number is even, otherwise false. You can call it like a normal method on any integer.
csharp
using System; public static class IntExtensions { public static bool IsEven(this int number) { return number % 2 == 0; } } class Program { static void Main() { int value = 10; bool result = value.IsEven(); Console.WriteLine($"Is {value} even? {result}"); } }
Output
Is 10 even? True
Common Pitfalls
- Extension methods must be in a
static class; forgetting this causes errors. - The extension method itself must be
static. - The first parameter must use
thiskeyword to specify the extended type. - Extension methods cannot access private members of the extended type.
- Be careful not to name extension methods the same as existing methods to avoid confusion.
csharp
/* Wrong: Missing static class */ // public class Extensions // { // public static bool IsPositive(this int number) => number > 0; // } /* Correct: Static class and method */ public static class Extensions { public static bool IsPositive(this int number) => number > 0; }
Quick Reference
Remember these key points when creating extension methods:
- Use
static classto hold extension methods. - Extension methods must be
static. - The first parameter uses
thiskeyword to specify the type extended. - Call extension methods like instance methods on the extended type.
Key Takeaways
Extension methods are static methods in static classes with the first parameter using 'this' to specify the extended type.
They let you add new methods to existing types without changing their source code.
Always place extension methods inside static classes and mark them static.
Extension methods cannot access private members of the extended type.
Use extension methods to write cleaner and more readable code by calling them like instance methods.