Search code examples
c#memberfunc

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 which contains a List of ClassB and a method to sum up the elements of classB. And classB possess two attribute memberX and memberY which are of double type. The func is to be use to choose which 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; }
}

Solution

  • You could try something like this:

    private double calculateSum(Func<ClassB, double> aFunction)
    {
        double theSum = 0;
        for (int i = 0; i < aList.Count(); i++)
        {
            theSum += aFunction(aList[i]);
        }
    
        return theSum;
    }
    

    Update

    If you really want to apply the func to the object to its left, then you could define an extension method.

    public static class ClassBExtensions
    {
        public static double Sum(this ClassB arg, Func<ClassB, double> func)
        {
            return func(arg);
        }
    }
    

    Then call it like this

    Func<ClassB, double> func = null; // define your func here
    for (int i = 0; i < aList.Count(); i++)
        {
            theSum += aList[i].Sum(func);
         }
     return theSum;