C# func<> applied to the object on left

I'm trying to figure out if there's a way to use func (or a similar method) applied to the left object. Ex.:

member1.MyFunction()

Here's a simplified context of usage. We got ClassA wich contains a List of ClassB and a method to sum up the elements of classB. And classB possess two attribute memberX and memberY wich are of double type. The func is to be use to choose wich member of ClassB we'd like to sum.

I've got an error in the line where I write

theSum += TheList[i].TheFunction();

The error is :

CS1061 C# does not contain a definition for and no extension method accepting a first argument of type could be found (are you missing a using directive or an assembly reference?)

Does anyone knows a workaround? My research could'not lead me to anything applied to the left side of the generic function.

public class ClassA
{
    public List<ClassB> TheList;
    public ClassA()
    {
        ClassB m1 = new ClassB(1, 2);
        ClassB m2 = new ClassB(1, 2);
        ClassB m3 = new ClassB(1, 2);
        TheList= new List<ClassB>() { m1, m2, m3 };
    }
    private double CalculateSum(Func<double> TheFunction)
    {
        double theSum = 0;
        for (int i = 0; i < TheList.Count(); i++)
        {
            theSum += TheList[i].TheFunction();
            // I'd like to use the previous line instead of having to write
            // a function for both of the following.
            // theSum += TheList[i].GetMember1();
            // theSum += TheList[i].GetMember2();
        }
        return theSum;
    }
}
public class ClassB
{
    private double memberX;
    private double memberY;
    public ClassB(double x, double y)
    {
        memberX = x;
        memberY = y;
    }

    public double GetMember1() { return memberX; }
    public double GetMember2() { return memberY; }
}
Jon Skeet
people
quotationmark

Well not with quite that syntax, but you can just use:

theSum += aFunction(aList[i]);

I suppose you could write an extension method for this, but the above is more idiomatic.

In fact, using LINQ to start with would be more idiomatic - your calculateSum method is already present in LINQ as Sum, so you could call:

double sum = aList.Sum(x => x.getMember1());

Of course more idiomatically, you'd use properties instead of methods:

double sum = aList.Sum(x => Member1);

Also for idiom, you'd make sure that any methods you do have follow .NET naming conventions, starting with a capital letter. I strongly advise you to start following naming conventions (even for throwaway demo code) immediately.

people

See more on this question at Stackoverflow