What are Extension Methods in C#?
🔹 What are Extension Methods in C#?
Extension methods allow you to add new methods to an existing type (class, struct, interface) without modifying its source code or using inheritance.
👉 You can call them as if they are instance methods of that type.
✅ Why do we need Extension Methods?
-
Add functionality to existing .NET classes (e.g.,
string,int,DateTime) -
Keep code clean and readable
-
Avoid inheritance for utility methods
-
Widely used in LINQ
🔑 Rules to Create Extension Methods
-
Must be created in a static class
-
Method must be static
-
First parameter must use
thiskeyword -
Namespace must be imported (
using)
🛠 How to Create an Extension Method (Step-by-Step)
Example 1: Extension Method for string
Step 1️⃣ Create a static class
Step 2️⃣ Use the extension method
🟢 Output:
🧠 How it Works Internally
This call:
Is actually compiled as:
📌 Example 2: Extension Method for int
Usage:
📌 Example 3: Extension Method for List<T>
Usage:
🔥 Extension Methods with Interfaces
Usage:
❌ What Extension Methods CANNOT Do
-
❌ Cannot access private members
-
❌ Cannot override existing methods
-
❌ If method name already exists → instance method wins
⚖ Extension Method vs Normal Method
| Feature | Extension Method | Normal Method |
|---|---|---|
| Modify existing class | ❌ No | ✔ Yes |
Uses this keyword | ✔ Yes | ❌ No |
| Belongs to class | Looks like it | Actually static |
| Access private data | ❌ No | ✔ Yes |
🎯 Real Interview Questions & Answers
❓ Q: Where are extension methods used in real projects?
✔ LINQ (Where, Select, OrderBy)
✔ Validation helpers
✔ Utility methods
✔ Clean architecture helper methods
❓ Q: Can extension methods be static?
✔ Yes, they must be static
❓ Q: Can we create extension methods for sealed classes?
✔ Yes (e.g., string)
❓ Q: Can extension methods be overloaded?
✔ Yes
❓ Q: What happens if both class method and extension method exist?
➡ Class method is called, not extension method.
🧠 Easy Memory Trick
Static class + static method + this keyword = Extension Method
Comments
Post a Comment