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

Extension method syntax in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Extension methods let you add new actions to existing things without changing their original code.

You want to add a new action to a class you cannot change.
You want to make your code easier to read by calling methods directly on objects.
You want to group helper methods that work on a certain type.
You want to keep your code organized without creating new subclasses.
Syntax
C Sharp (C#)
public static class ClassName
{
    public static ReturnType MethodName(this Type parameter, OtherParameters)
    {
        // method body
    }
}

The first parameter has this before the type to mark it as an extension method.

Extension methods must be inside a static class.

Examples
This adds a WordCount method to all strings.
C Sharp (C#)
public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        return str.Split(' ').Length;
    }
}
This adds an IsEven method to all integers.
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#";
        int count = sentence.WordCount();
        Console.WriteLine($"Word count: {count}");
    }
}
OutputSuccess
Important Notes

Extension methods look like normal methods when called, but they are static methods behind the scenes.

If a class already has a method with the same name and parameters, the class method is used instead of the extension.

Summary

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

They must be static methods inside static classes, with this before the first parameter.

They make code cleaner and easier to read by allowing method calls directly on objects.