C# Generic Type Constraints?

Since both double and List arrayOrList) { // use foreach to loop through arrayOrList and calculate the average } That's simple subtype polymorphism, no generics required As others have already mentioned, if you simply want to calculate an average such a method already exists in the framework.

Since both double and List implement IEnumerable, I'd suggest the following: public double Average(IEnumerable arrayOrList) { // use foreach to loop through arrayOrList and calculate the average } That's simple subtype polymorphism, no generics required. As others have already mentioned, if you simply want to calculate an average, such a method already exists in the framework.

– Jon Aug 11 at 21:51 @Jon: If you really need different code for array and list, the "correct" solution would be to create two overloads Average(double) and Average(List). That way, you don't need any dynamic type checks at all. If you have common code, put that in a third (private) method that accepts an IEnumerable, which is called by both of your overloads.

Note that, if you just want to calculate the average, you don't need to determine if it's an array or a list. – Heinzi Aug 12 at 6:31 Thanks Heinzi, your answer worked great for the average method but I have another that requires me to sort the array. I am using .

NET 2.0 so I can't use Enumerable.OrderBy() so I was looking for the best way to convert it back to either an array or list and then sort it. But it sounds like overloading the method may be the preferred way? – Jon Aug 12 at 14:09 @Jon: Yes, overloading sounds like the correct solution.

In particular, since there are already specific methods in the . Net Framework (even 2.0) for sorting an array (msdn.microsoft. Com/de-de/library/aw9s5t8f.

Aspx) and a list (msdn.microsoft.Com/en-us/library/w56d4y5z. Aspx). – Heinzi Aug 15 at 6:43.

I would just use IEnumerable, since all you need to do is loop over the data (and both lists and arrays support this, as do deferred sequences). In fact, Microsoft got there first: var avg = sequence.Average(); msdn.microsoft.com/en-us/library/bb35894....

Then if you really want to use an ArrayList, I assume not by choice you can use the AsEnumerable() extensions. EDIT, seems I miread ArrayOrList, but the answer still applies, although it was 56 secs late.

Var x = new List(); var average = x.Average(); var y = new Double10; var average = y.Average().

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions