Extension Methods in C#

In this tutorial, we'll explore the topic of extension methods in C#. We'll cover topics like an introduction, practical examples of when to use a static method instead of an extension method when applying an extension method in C#, important principles to keep in mind, the advantages of using extension methods, and applications in the end. So, without any more delay, let's begin discussing the subject.

What exactly is the C# extension method?

It is possible to add additional methods to existing classes in C# without changing their source code thanks to a feature known as an extension method.

You can use it to create brand-new methods that can be applied in the same manner as the original class's regular methods.

Static methods are those specified in a static class. For the first parameter, they employ the "this" keyword to denote the type expansion by the extending method.

The extension method can extend classes from outside libraries or frameworks without altering their original code. It enables you to improve the functioning of outside code without creating problems or breaking compatibility.

Syntax:

public static class MyExtensions


{


    // Define an extension method for an existing type


    public static ReturnType NewMethod(this ExistingType existingInstance, parameters)


    {


        // Method implementation


    }


}

Extension method in C# Example:

The string type is an inbuilt class in the.net framework, as we all know. Because the full source code for this type of class is not available, we can update the source program code of the string class. Our requirement is to add a function to the string class, namely GetWordCount(). This method returns a count of words in a string.

Example 1:

using System;


public static class StringExtensions


{


    // Extension method for string to reverse its content


    public static string ReverseString(this string input)


    {


        char[] charArray = input.ToCharArray();


        Array.Reverse(charArray);


        return new string(charArray);


    }


}


class Program


{


    static void Main()


    {


        string originalString = "Hello, world!";


        string reversedString = originalString.ReverseString();


        Console.WriteLine($"Original String: {originalString}");


        Console.WriteLine($"Reversed String: {reversedString}");


    }


}

Output:

Extension Methods in C#

Example 2:

using System;


public class Person


{


    public string FirstName { get; set; }


    public string LastName { get; set; }


    public Person(string firstName, string lastName)


    {


        FirstName = firstName;


        LastName = lastName;


    }


}


public static class PersonExtensions


{


    // Extension method to get the full name of a Person


    public static string GetFullName(this Person person)


    {


        return $"{person.FirstName} {person.LastName}";


    }


}


class Program


{


    static void Main()


    {


        Person person = new Person("John", "Doe");


        // Using the extension method to get the full name


        string fullName = person.GetFullName();


        Console.WriteLine($"Full Name: {fullName}");


    }


}

Output:

Extension Methods in C#

When to refer to extension methods as static methods?

There are still cases where an extension method must be used as a static method:

  • Using a member technique to resolve disagreement. The above may arise if the latest edition of a library adds a novel member method with a similar signature. The compiler will choose the member method in this scenario.
  • Handling conflicts with a different extension method with a similar signature. This is possible if two libraries offer alike extension methods and the namespaces for both classes having extension methods have been utilized in the same file.
  • Sending extension method as a method group via delegate parameter.
  • Using Reflection to do your own binding.
  • In Visual Studio, use the extension method in the Instant window.

Important factors to keep in mind:

  1. Only the static class can define extension methods.
  2. When attached to a class or structure, extension methods cease to be static methods and are instead specified as non-static methods.
  3. The binding argument is the first parameter of an extension method. It must be the name of the class to which the method must be bound, and the binding keyword must precede it will be specified using a regular argument starting from the second position in the parameter list.
  4. If necessary, an extension method will be specified using a regular argument starting from the second position in the parameter list.
  5. By incorporating the extension method's namespace, extension methods may be used everywhere in the program.
  6. The extension method does not support method overriding.
  7. It needs to be declared in a static top-level class.
  8. It is inapplicable to fields, properties, or events.

The Benefits of C# Extension Methods:

  1. Reusability: Extension methods increase code reusability by letting you develop a method one time and use it throughout numerous projects.
  2. Flexibility: Extension methods enable you to extend already existing classes without using inheritance, giving you even more design flexibility.
  3. Readability: Extension methods improve code readability by allowing you to invoke additional methods on objects in a more natural and logical way.
  4. Encapsulation: Extension methods aid in the organization of related functionality by separating it into different classes, facilitating code maintenance and reworking.
  5. Integrate: Extension methods integrate smoothly with existing source code, which makes them an effective tool for extending functionality in external libraries or frameworks.

In short, extension methods in C# allow you to add new functionality to preexisting classes, simplify code reusability and readability, improve code organization, provide design flexibility, and extend other code smoothly.

Extension Method Applications in C#:

  • The extension method offers novel features to already existing classes without altering their original code.
  • It can let you extend built-in.NET Framework classes.
  • By introducing custom methods, the extension technique can be used to improve third-party libraries or frameworks.