This extension method will return the value to a given type:
public static T Val<T>(this object expression) where T : IConvertible { T retVal = default(T); if (expression != null) { var regEx = new Regex(@"^([0-9]|-|\+|,|\$|\.){1,}"); if (regEx.IsMatch(expression.ToString().Trim())) { var match = regEx.Match(expression.ToString().Trim()).Groups[0].Value.Replace("--", "-"); var returnType = retVal.GetType(); // intergers can not have decimal points in the // removes the part of the string from the decimal point afterword if (returnType.Name.StartsWith("Int") && match.Contains(".")) { match = match.Substring(0, match.IndexOf(".")); } retVal = (T)Convert.ChangeType(match, returnType); } } return retVal; } |