Add extension method to existing object - CSharp Custom Type

CSharp examples for Custom Type:Extension Methods

Description

Add extension method to existing object

Demo Code

using static System.Console;
using System;/*from  w ww  .jav a  2s. c  o m*/
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
   static void Main(string[] args)
   {
      string email1 = "pamela@test.com";
      string email2 = "ian&test.com";
      WriteLine($"{email1} is a valid e-mail address: {StringExtensions.IsValidEmail(email1)}.");
      WriteLine($"{email2} is a valid e-mail address: {StringExtensions.IsValidEmail(email2)}.");
      WriteLine($"{email1} is a valid e-mail address: {email1.IsValidEmail()}.");
      WriteLine($"{email2} is a valid e-mail address: {email2.IsValidEmail()}.");
   }
}
public static class StringExtensions
{
   public static bool IsValidEmail(this string input)
   {
      // use simple regular expression to check
      // that the input string is a valid email
      return Regex.IsMatch(input,
      @"[a-zA-Z0-9\.-_]+@[a-zA-Z0-9\.-_]+");
   }
}

Result


Related Tutorials