1) add an extention to a string to check if this string is a valid email address
public static class StringExtensions
{
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
}
it takes one static class and a method to pass in the original object as "this". Done.
To use the above extention
Using StringExtensions;
string email="kelly.qu@123.com"
if (email.IsValidEmailAddress()) //this method would also show in the intellisense
...
2) more advanced extention - check and see if this object is in a collection?
using System;
using System.Collections;
public static class ListExtensions
{
public static bool in(this Object o, IEnumerable c)
{
return c.Any(x=>x.equals(o));
}
}
To test above extention:
using System;
Using ListExtensions;
public class test
{
public void testExtension()
{
string[] vals = {"baltimore", "toronto", "shanghai"};
if ("Portland".in(vals)) // check if Portland is in the list?
}
}
No comments:
Post a Comment