Learn about Extensions in C#

Introduction

It is possible to add new methods to a class without altering the class's source code, thanks to a new feature that was added to C# 3.0. For example, if a class has a set of members, you can add more methods to it in the future without having to change the class's source code.

If the class's source code is unavailable or we lack authorization to make changes to it, we may utilize extension methods to expand its capabilities in the future.

Inheritance is a method for expanding a class's functionality prior to extension methods. For example, to add new members to an existing class without changing the class itself, we define a child class to the existing class and then add new members to the child class.

When we use an extension method, we will increase a class's capabilities. In this instance, we will make a new class and use it to increase the capabilities of an already existing class.

In contrast to inheritance, which calls methods defined in both the old and new classes using the object of the new class, extension methods call methods defined in both the old and new classes using the object of the old class. Both approaches can be used to expand the functionality of an existing class.

Note. Inherited rights are not always guaranteed. This implies that we are unable to create a derived class from the sealed if the class is declared with the sealed modifier. However, we can use the Extension Method to increase the sealed class's capabilities.

Create the extension methods in C#

public static class StringExtensions
{
    public static bool IsValidName(this string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return false;
        }
        // Basic regex for a name, assuming it consists of letters, spaces, hyphens, and apostrophes
        // You may need to adjust this based on your specific requirements
        string pattern = @"^[a-zA-Z]+(?:[-' ][a-zA-Z]+)*$";
        // Using Regex.IsMatch to check if the name matches the pattern
        return Regex.IsMatch(value, pattern);
    }
    public static bool CheckLength(this string value, int length = 20)
    {
        // Check if the length of the name is less than or equal to the provided length
        return value.Length <= length;
    }
}
public static class NumberExtensions
{
    public static bool IsValidNumber(this string number)
    {
        // Regex pattern for validating phone numbers
        string pattern = @"^\+?\d{10,15}$";     
        // Using Regex.IsMatch to check if the phone number matches the pattern
        return Regex.IsMatch(number, pattern);
    }
}

In the above example, I have used a couple of scenarios, like the string extension method and number validation.

var name = "Jaimin";
var number = "7990233523";
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("{0}: {1}", name, name.IsValidName());
Console.WriteLine("{0}: {1}", name, name.CheckLength());
Console.WriteLine("{0}: {1}", name, name.CheckLength(5));
Console.WriteLine("{0}: {1}", number, number.IsValidNumber());

Number validation

Extensions method chaining

public static string Pluralize(this string value)
{
    ArgumentNullException.ThrowIfNull(value, nameof(value));
    // Simple pluralization rule: add "s" to the end of the singular form
    return $"{value}s";
}
public static string Base64(this string value)
{
    ArgumentNullException.ThrowIfNull(value, nameof(value));
    // Encode the string to Base64
    return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
}

Extension method

Key points about extension methods

Although it is referred to as an instance method, an extension method is specified as a static method.

The "this" keyword comes before the first parameter of an extension method, which defines the type of the extended object.

Since an extension method has a lesser priority than an instance method, it will never be invoked, even if it has the same name and signature.

The current instance methods cannot be overridden by an extension method.

Fields, properties, and events cannot be utilized using an extension method.

If two extension methods with the same name and signature are defined in two separate namespaces and these namespaces are included in the same class file using directives, the compiler does not generate an error. If you attempt to invoke an extension method, the compiler will generate an error.

Benefits of extension methods

It makes it possible to extend pre-existing classes without requiring inheritance or modifying the source code of the class.

Extending its functionality is not a concept if the class is sealed. To address this, a novel idea—extension methods, to be exact—is presented.

It is employed in the design of your class to provide dynamic elements to the C# upgrades.

FAQs


Q 1. In C#, what is an extension method?

By using extension methods, you can "add" methods to preexisting types without having to rebuild the original type, recompile it, or make any other changes.

Q 2. What are methods in C# that extend?

Without recompiling, generating a new derived type, or changing the original type in any other way, developers can increase the functionality of an existing type using a C# extension method.

Q 3. What does the C# extension method include?

The idea of an extension method in C# enables you to add additional methods to an existing class or structure without changing the original type's source code.

We learned the new technique and evolved together.

Happy coding!


Recommended Free Ebook
Similar Articles