I'm trying to not repeat code unnecessarily. I have this method which I want to return true or false based on a basic calculation. The arguments for the value could be double
, float
, decimal
.
This was my (failed) attempt. Any guidance would be appreciated.
private bool DoMyThingGeneric(Type type, object value)
{
// I'm trying to do something like this:
// cast "value" to "type"
var constructed = type.MakeGenericType();
object obj = Activator.CreateInstance(constructed);
// assign "value" to "d" - THIS DOESN'T WORK
var endVal = obj as typeof(type);
if (Math.Floor(endVal * 1000) == endVal * 1000)
{
return true;
}
return false;
}
private bool DoMyThing(decimal x)
{
DoMyThingGeneric(x.GetType(), x);
return false;
}
private bool DoMyThing(float x)
{
DoMyThingGeneric(x.GetType(), x);
return false;
}
private bool DoMyThing(double x)
{
DoMyThingGeneric(x.GetType(), x);
return false;
}
Repeat the code. Or cast.
As generics can not have operators.... there is no alternarive.
In C#, you have the following options.
double
and float
, you could implement support for float
by calling the double
method and casting the result to float
). This is not always an option since the range and precision of the various types doesn't always overlap.dynamic
arguments. This would avoid some code duplication at the expense of type safety and have a substantial performance impact.Most application code involving a choice between float
, double
, and decimal
is either so simple that it is easily duplicated, or so performance sensitive that duplication is required to meet the target goals. Repeating the code is almost always the best available option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With