views:

47

answers:

2

I wonder if I can do assignment using TResult<in T, out TResult> I can retrieve the value of the property of a class instance with that delegate as below:

class Program
{
    class MyClass
    {
        public int MyProperty { get; set; }
    }

    static void Main(string[] args)
    {
        Func<MyClass, int> orderKeySelector = o => o.MyProperty;
        MyClass mc = new MyClass() { MyProperty = 3 };

        int val = orderKeySelector.Invoke(mc);
    }
}

I want to assign some value to MyProperty using orderKeySelector and MyClass instance. Any Ideas?

A: 

Your Func<,> delegate represents the property getter. If you want a property setter, you need Action<MyClass, int>, like this:

Action<MyClass, int> setter = (o, value) => o.MyProperty = value;
Jon Skeet
It Worked. Thanks.
Musa Hafalır
A: 

You can't do it with orderKeySelector as it stands, but you could create a separate setter delegate:

MyClass mc = new MyClass() { MyProperty = 3 };

Func<MyClass, int> orderKeySelector = o => o.MyProperty;
int val = orderKeySelector(mc);

Console.WriteLine(val);    // 3

Action<MyClass, int> orderKeySetter = (o, v) => o.MyProperty = v;
orderKeySetter(mc, 42);

Console.WriteLine(mc.MyProperty);    // 42
LukeH
It works. Thanks for your detailed explaination.
Musa Hafalır