Monday 12 October 2009

Example Useful C# Extension Functions

Here are a few extension functions that I find useful:


public static bool IsNullOrEmpty(
this string expression )
{
bool result = string.IsNullOrEmpty(
expression );
return result;
}

public static string ToFormat(
this string expression, params object[] args )
{
string result = String.Format(
expression, args );
return result;
}

public static bool IsValidEmailAddress(
this string expression )
{
bool result = BaseRegexHelper.IsValid(
expression, emailRegex );
return result;
}

public static bool IsValidGuid(
this string expression )
{
bool result = BaseRegexHelper.IsValid(
expression, guidRegex );
return result;
}

The latter two functions call this method:

public static bool IsValid(
string input, string pattern )
{
bool isValid = false;

if( input != null )
{
string trimmedExpression =
input.Trim();

if( trimmedExpression.Length > 0 )
{
Regex regexGuid = new Regex(
pattern, RegexOptions.IgnoreCase );
isValid = regexGuid.IsMatch(
trimmedExpression );
}
}

return isValid;
}

1 comment:

Hugonne said...

Nice article. Here's a blog entry I wrote on extensions methods for strings and enum values:

http://hugonne.blogspot.com/2010/01/enums-and-string-values.html

Hope it helps as well.