Is there a clever way to call a type dependent extension method dynamically?

Viewed 217

The code below will compile but fails at runtime. It's provided just to give an idea of what I'm trying to do. What I would like to do is create a method that accepts a collection of objects (effectively an "untyped" collection) and if this collect is comprised of numbers of a single type return the mean using the Average() extension method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nnConsole {
    class Program {
        static void Main(string[] args) {
            var ints = new object[4] { 1, 2, 3, 4 };
            var dbls = new object[4] { 1.0, 2.0, 3.0, 4.0 };
            Console.WriteLine(ReallyMean(ints));    
            Console.WriteLine(ReallyMean(dbls));    
            }

        static public double ReallyMean(ICollection<object> data) {
            var unique = data.Distinct();
            var types = unique.Select(x => x.GetType()).Distinct();
            if (types.Count() == 1) {
                if (types.First().IsValueType) {
                    /***********************
                     * magic here to create ddata var that will
                     * call the appropriate extension method for average */ 
                    dynamic ddata = data; // DOES NOT WORK
                    return ddata.Average();
                    }
                }
            return double.NaN;
            }
        }
    }

I'm sure I could use reflection to find the appropriate Average method and invoke it (not pretty). Is there a shorter/cleaner/better way to do this? I can use the latest C# and .NET runtime.

3 Answers
Related