You can create an extension for Object that returns a bool for you, for example (untested, can provide false positives, etc.) (catches decimal numbers, float, ints, using the US style delimiter for a decimal number, modifies the regular expression to match hex , etc.)
public static class Object { static Regex r = new Regex(@"^\d*\.*\d$", RegexOptions.Compiled); public static bool IsNumber(this object obj) { return r.IsMatch(obj.ToString() && !(obj is string); } }
Since ToString is part of Object, and everything is ultimately a child of the object ...
Of course, this will not provide security such as generics or something like that, but it will still allow you to do such things with a little more work. You did not indicate what the base class is for, whether you want to accept a numeric type as an argument somewhere, or if you need generics. This can lead you to participate anywhere you go.
Using:
public class thingThatHasNumericValue { private object arbNumber; public object SomeArbitraryNumber { get { return arbNumber; } set { if (!arbNumber.IsNumber()) { throw new InvalidOperationException("Must be a number"); } arbNumber = value; } } }
Chad ruppert
source share