0
0
C Sharp (C#)programming~5 mins

Why extension methods are needed in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Extension methods let you add new actions to existing things without changing them. This helps keep your code simple and organized.

You want to add a new action to a class you cannot change, like a built-in type.
You want to keep your code clean by grouping related actions together.
You want to make your code easier to read by calling new actions directly on objects.
You want to add helper actions that feel like they belong to the original class.
You want to avoid creating many small helper classes just to add one action.
Syntax
C Sharp (C#)
public static class ClassName {
    public static ReturnType NewAction(this ExistingType obj, OtherParameters) {
        // code here
    }
}

The method must be inside a static class.

The first parameter uses this keyword to specify the type being extended.

Examples
This adds a WordCount action to strings to count words.
C Sharp (C#)
public static class StringExtensions {
    public static int WordCount(this string str) {
        return str.Split(' ').Length;
    }
}
This adds an IsEven action to integers to check if they are even.
C Sharp (C#)
public static class IntExtensions {
    public static bool IsEven(this int number) {
        return number % 2 == 0;
    }
}
Sample Program

This program adds a WordCount method to strings and uses it to count words in a sentence.

C Sharp (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 sentence = "Hello world from C#";
        Console.WriteLine($"Word count: {sentence.WordCount()}");
    }
}
OutputSuccess
Important Notes

Extension methods do not change the original class or its source code.

They help keep your code organized and easy to read.

Use extension methods wisely to avoid confusion about where methods come from.

Summary

Extension methods add new actions to existing types without changing them.

They make code cleaner and easier to use.

They are defined as static methods in static classes with this on the first parameter.