Search code examples
c#generic-programming

C# templating access to object members


I want to be able to create a function that does a generic action on any member variable.

class line
{
    double angle;
    double length;
    public void add(reference member, double scalar)
    {
        this.member *= scalar;
    }
}

Is this possible in C#. If I have many member variables, I don't want to create a giant switch case. I also don't want to create one lambda function for each member variable seeing as the operation would be the same.


Solution

  • Building off of @askpark's answer I've come up with something simpler

    class line
    {
        double angle;
        double length;
    
        public void delegate adder(line l, double d);
        static adder angleAdder = (l,d) => {l.angle += d};
        static adder lengthAdder = (l,d) => {l.length += d};
    
        public void add(adder addFunc, double scalar)
        {
            addFunc(this, scalar);
        }
    }