Re: MinMaxArray
- From: Jeroen Mostert <jmostert@xxxxxxxxx>
- Date: Wed, 09 Jul 2008 11:48:30 +0200
Ondrej Medek wrote:
I would like to have a generic class MinMaxArray<T>, which is aArrays are immutable. Do you need a mutable collection? The values are easy enough to calculate for any collection after it's created. LINQ offers extension methods to do this directly, actually, so you can write a.Average() for any array of numerical types. Incorporating this in a wrapper to cache the calculated values is easy.
wrapper around an array of T[] and computes minimum, maximum, and
average value from the array T[]. I need it only for the basic numeric
types (int, float, etc.).
I had problems with operators < > + and /, when I was computingBasically, the .NET type system isn't extensive enough to do what you want directly. There is no INumeric interface that all primitive numeric types implement. IComparable and IEquatable are not sufficient for the operations you want. You can use Decimal as a generic integral type, but there's no equivalent for float and double.
minimum, maximum and average values. I have errors like "Operator ...
cannot be applied to operans of type 'T' and 'T'." So, I use
IComparer<T> instead of operators < >, but I do not know, how to
compute average value (sum and divide) for a generic numeric type T.
Is there any easy way to do it? Disable the type checking in the
compile time?
In short, you can't really use generics here without resorting to ugly code like this:
if (typeof(T) == typeof(int)) {
T result = (T) (((int) t1) / ((int) t2));
}
This works, but it's not winning any safety or readability prizes. There are various ways of mitigating this, but they're all more or less trying to fit a square peg in a round hole.
--
J.
.
- Follow-Ups:
- Re: MinMaxArray
- From: Marc Gravell
- Re: MinMaxArray
- From: Jeroen Mostert
- Re: MinMaxArray
- References:
- MinMaxArray
- From: Ondrej Medek
- MinMaxArray
- Prev by Date: Re: MinMaxArray
- Next by Date: Re: MinMaxArray
- Previous by thread: Re: MinMaxArray
- Next by thread: Re: MinMaxArray
- Index(es):
Relevant Pages
|