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?
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?
3 Answers
Reset to default 3This is specifically a limitation of object initializers. But you can do it outside of the initializer context:
class B
{
public B()
{
var a = new A();
a.Param = 100;
a.DoSomething = () => Debug.Print(a.Param);
}
}
Of course, now you have a closure, which is an additional object behind the scenes. Additionally, this requires DoSomething
to be public, which means this can be changed later, while the object initializer would allow a property with an init
option.
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.
You can use a.Param
rather than using this.Param.
class B
{
public B()
{
var a = new A()
{
Param = 100,
DoSomething = () => Debug.Print(a.Param)
};
}
}
Action
from being referenced from multiple properties in multiple objects. There's no clear concept of "the" owner within the system. – Damien_The_Unbeliever Commented Feb 27 at 15:10this
is dynamically bond at run time, so I'm curious on whether C# has similar language feature. – Jake Commented Feb 27 at 15:13a
of typeA
that you have assignedParam
andDoSomething
to, nothing stops me from writingvar otherA = new A { Param = a.Param==0 ? 99 : 0, DoSomething = a.DoSomething };
. There are now two "the owner"s of thatDoSomething
Action
and they have different opinions on whatParam
is equal to. – Damien_The_Unbeliever Commented Feb 27 at 15:13