Last Updated: August 01, 2023
·
956
· rafaelune

Extension Methods C#

Extend native classes or your own classes to support new action methods.

For example, let's extend String class to check if its value is a valid email:


public static class StringExtensions
{

    public static bool IsValidEmail(this string email)
    {
        Regex regex = new Regex(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");
        return regex.IsMatch(email);
    }

}

Now you should use it this way:


string email = "john@email.com";
if (email.IsValidEmail())
{
                    // ... performs some action
}

If you wanna more about: https://www.google.com/?q=extension+methods+c%23

:)