System.Action<T>
is a delegate, basically meaning that using it you can define any method to be called as long as the signature is the same. In your example the
Action<int>
parameter defines the types to be used so you need a method that has the signature as
void SomeMethod(int parameterValue)
Now in the calling code you have an anonymous method stored in a variable
setPropertyValue1
Action<int> setPropertyValue1 = (value) =>
{ class1.PropertyValue1 = value; };
The method above gets one integer value (named
value
) as a parameter and whenever called the code assigns the value from the parameter to class1.PropertyValue1 in other words when called, the code below is executed
{ class1.PropertyValue1 = value; }
Now since a 'pointer' to this method is stored in the
setPropertyValue1
it can be used as a parameter to the next call. The main method calls
class2.UpdateProperty(setPropertyValue1);
That means that the method in
Class2
actually calls the anonymous method described earlier. The call from Class2 is
setValue(100);
so that means that the anonymous method is called using 100 as the parameter value.
From what I gather from the things you have tried, it looks like you want to set the value from outside
Class2
. If that is the case, then modifying the code slightly, would probable be what you're looking for
static void Main(string[] args) {
Class1 class1 = new Class1();
Class2 class2 = new Class2();
Action<int> setPropertyValue1 = (value) =>
{ class1.PropertyValue1 = value; };
class2.UpdateProperty(setPropertyValue1, 50);
Console.WriteLine(class1.PropertyValue1);
}
class Class1 {
public int PropertyValue1 { get; set; }
}
class Class2 {
public void UpdateProperty(Action<int> setValue, int valueToSet) {
setValue(valueToSet);
}
}