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

  1. Must be created in a static class

  2. Method must be static

  3. First parameter must use this keyword

  4. 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

public static class StringExtensions { public static int WordCount(this string str) { if (string.IsNullOrEmpty(str)) return 0; return str.Split(' ').Length; } }

Step 2️⃣ Use the extension method

class Program { static void Main() { string text = "C sharp interview preparation"; int count = text.WordCount(); Console.WriteLine(count); } }

🟢 Output:

3

🧠 How it Works Internally

This call:

text.WordCount();

Is actually compiled as:

StringExtensions.WordCount(text);

📌 Example 2: Extension Method for int

public static class IntExtensions { public static bool IsEven(this int number) { return number % 2 == 0; } }

Usage:

int n = 10; Console.WriteLine(n.IsEven()); // true

📌 Example 3: Extension Method for List<T>

public static class ListExtensions { public static void PrintAll<T>(this List<T> list) { foreach (var item in list) Console.WriteLine(item); } }

Usage:

var list = new List<int> { 1, 2, 3 }; list.PrintAll();

🔥 Extension Methods with Interfaces

public interface ILogger { void Log(string msg); } public static class LoggerExtensions { public static void LogInfo(this ILogger logger, string msg) { logger.Log("INFO: " + msg); } }

Usage:

ILogger logger = new ConsoleLogger(); logger.LogInfo("Application started");

❌ 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

FeatureExtension MethodNormal Method
Modify existing class❌ No✔ Yes
Uses this keyword✔ Yes❌ No
Belongs to classLooks like itActually 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

Popular posts from this blog

.NET Core Interview Questions and Answers for 10+ Years Experienced Professionals

What are SOLID Principles?

.NET Core Senior Interview Q&A