I'm trying to write a code that not only is easy to read, but also flexible. To do so I'm using interfaces more often. For instance, instead of having a List as parameter of a method, I'm using IEnumerable whenever possible.
But check this method
public static Color MeanColor(this IEnumerable<Color> list) {
var colors = list as Color[] ?? list.ToArray();
if (!colors.Any()) {
// Gray is the mean of all colors (Black+White/2)
return Color.FromArgb(127, 127, 127);
}
var r = 0;
var g = 0;
var b = 0;
foreach (var c in colors) {
r += c.R;
g += c.G;
b += c.B;
}
return Color.FromArgb(r / colors.Length, g / colors.Length, b / colors.Length);
}
Since I need to use the Length method/property, I can't just use a IEnumerable. Therefore I check if it's a array, and if it's not I convert it to one using the ToArray() method.
I tried using a 'count' variable inside the foreach loop, like this
int count = 0;
foreach (var c in colors) {
r += c.R;
g += c.G;
b += c.B;
count++;
}
But the performance hit is greater than converting a 50000 element List to and array.
So I'd like to know: is it possible to 'ask an object' if it has a method "X'? Is this case, "ask" the object if it has a Count property or GetLength() method.
edit: Tim's answer does solve my problem, in this case. But the question remains, is it possible to ask an object has a specific method/property?