Reputation: 7308
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;
}
Upvotes: 4
Views: 2579
Reputation: 4636
Using the dynamic keyword will work for you...
private bool DoMyThing<T>(T x)
{
if (Math.Floor((dynamic) x*1000) == (dynamic) x*1000)
return true;
return false;
}
Bear in mind that you lose compile time type safety and some performance... it just depends on if the trade-offs are worth it for your case.
Upvotes: 1
Reputation: 99869
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.
Upvotes: 4
Reputation: 62093
Repeat the code. Or cast.
As generics can not have operators.... there is no alternarive.
Upvotes: 4