Search code examples
c#object-initializers

In C#, is it possible to get the owner object's properties from an anonymous function that is assigned outside?


Let's assume we have a class defined as:

class A
{
    public int Param { get; set; }
    public Action DoSomething { get; set; }
}

The DoSomething action is assigned in another class, but it needs to have access to param:

class B
{
    public B()
    {
        var a = new A()
        {
            Param = 100,
            DoSomething = () => Debug.Print( xxx ) // xxx here needs to refer to Param
        };
    }
}

Clearly, this.Param won't work because this is lexically bond to class B. How can I make DoSomething to access its owner class's other properties?


Solution

  • A simple solution is to take a parameter representing Param

    class A
    {
        public int Param { get; set; }
        public Action<int> DoSomething { private get; set; }
        void RunDoSomething() => DoSomething(Param);
    }
    ...
    var a = new A()
    {
        Param = 100,
        DoSomething = param => Debug.Print( param ) 
    };
    
    

    Or you could use an Action<A> to essentially get an this reference.