c# - Is there something in the .NET Framework to check if a value fits into a type? -
i need find out if decimal value fit type (the destination type detected @ runtime) , truncate max or min value if not can send thru network.
i avoid big switch sentences types , thought maybe there in .net framework.
this action has name in signal processing: clipping.
and here there totally useless decimalrestrictor<t>, based on dinamically built expression tree in form
x => x <= min ? min : x >= max ? max : (t)x; plus exception decimal, float , double: 3 types can accept decimal value.
the code:
public static class decimalclipper<t> { public static readonly func<decimal, t> clip; static decimalclipper() { parameterexpression value = expression.parameter(typeof(decimal), "value"); expression<func<decimal, t>> lambda; if (typeof(t) == typeof(decimal)) { lambda = expression.lambda<func<decimal, t>>(value, value); } else if (typeof(t) == typeof(float) || typeof(t) == typeof(double)) { lambda = expression.lambda<func<decimal, t>>(expression.convert(value, typeof(t)), value); } else { t min = (t)typeof(t).getfield("minvalue", bindingflags.static | bindingflags.public).getvalue(null); expression mint = expression.constant(min); expression mindecimal = expression.constant(convert.todecimal(min)); t max = (t)typeof(t).getfield("maxvalue", bindingflags.static | bindingflags.public).getvalue(null); expression maxt = expression.constant(max); expression maxdecimal = expression.constant(convert.todecimal(max)); unaryexpression cast = expression.convert(value, typeof(t)); conditionalexpression greaterthanorequal = expression.condition(expression.greaterthanorequal(value, maxdecimal), maxt, cast); conditionalexpression lesserthanorequal = expression.condition(expression.lessthanorequal(value, mindecimal), mint, greaterthanorequal); lambda = expression.lambda<func<decimal, t>>(lesserthanorequal, value); } clip = lambda.compile(); } } public static class decimalex { public static t clip<t>(this decimal value) { return decimalclipper<t>.clip(value); } } i'm including extension method...
examples of use:
int i1 = decimal.maxvalue.clip<int>(); int i2 = decimal.minvalue.clip<int>(); int i3 = 5.5m.clip<int>(); int i4 = -5.5m.clip<int>(); byte i5 =(-5.5m).clip<byte>(); //char i6 = decimal.maxvalue.clip<char>(); float i7 = decimal.maxvalue.clip<float>(); double i8 = decimal.maxvalue.clip<double>(); decimal i9 = decimal.maxvalue.clip<decimal>(); ah... expression tree generated once each type t used , cached working of generic types , static members.
the char, intptr, uintptr aren't supported @ time.
Comments
Post a Comment