Extension Methods in C# 3.0

7. April 2008
One of the coolest features of C# 3.0 is Extension Methods.  Basically, an extension method is a static method that can extend a given type (even if that type is closed).  The following extension method adds a .ValidateRegularExpression() method to the String object. 
		public static bool ValidateRegularExpression(this string validationData, string regularExpression)
			if (!IsBlank(validationData))
			{
				System.Text.RegularExpressions.Regex re;
				
				try
				{
					re = new System.Text.RegularExpressions.Regex(regularExpression);
					
					return re.IsMatch(validationData);
				} 
				catch (System.Exception) 
				{
					return false;
				}
				finally
				{
					re = null;
				}
			}
			
			return false;
	        } 

Development

Comments are closed