IntroductionIn this code snippet i have given no of useful examples extension methods with C#. The extension methods help to us rewrite code again and again. And also it does adapt with existing class and object. Codeusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{class ExtensionSamples
{public static bool IsWholeNumber(this string strNumber)
{if (strNumber == "")return false;
Regex objNotWholePattern = new Regex("[^0-9]");return !objNotWholePattern.IsMatch(strNumber);
}public static bool IsDouble(this string strNumber)
{if (strNumber == "")return false;try{
Convert.ToDouble(strNumber);
}catch (Exception)
{return false;
}return true;
}public static bool IsAlphaNumeric(this string strToCheck)
{bool valid = true;if (strToCheck == "")return false;
Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
valid = !objAlphaNumericPattern.IsMatch(strToCheck);return valid;
}public static bool IsValidAlphaNumericWithSpace(this string strToCheck)
{bool valid = true;if (strToCheck == "")return false;
Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9\\s]");
valid = !objAlphaNumericPattern.IsMatch(strToCheck);return valid;
}public static bool IsValidAlphabetWithSpace(this string strToCheck)
{bool valid = true;if (strToCheck == "")return false;
Regex objAlphaNumericPattern = new Regex("[^a-zA-Z\\s]");
valid = !objAlphaNumericPattern.IsMatch(strToCheck);return valid;
}public static bool IsValidAlphabetWithHyphen(this string strToCheck)
{bool valid = true;if (strToCheck == "")return false;
Regex objAlphaNumericPattern = new Regex("[^a-zA-Z\\-]");
valid = !objAlphaNumericPattern.IsMatch(strToCheck);return valid;
}public static bool IsAlpha(this string strToCheck)
{bool valid = true;if (strToCheck == "")return false;
Regex objAlphaPattern = new Regex("[^a-zA-Z]");
valid = !objAlphaPattern.IsMatch(strToCheck);return valid;
}public static bool IsNumber(this string strNumber)
{try{
Convert.ToDouble(strNumber);return true;
}catch{return false;
}
}public static bool IsInteger(this string strInteger)
{try{
Convert.ToInt32(strInteger);return true;
}catch{return false;
}
}public static bool IsDateTime(this string strDateTime)
{try{
Convert.ToDateTime(strDateTime);return true;
}catch{return false;
}
}public static bool isEmail(this string inputEmail)
{if (inputEmail != null && inputEmail != "")
{string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);if (re.IsMatch(inputEmail))return (true);elsereturn (false);
}elsereturn (false);
}
}
}
I hope this is help to you all.thank you for reading |