Given the following code;
public class CustomControl {
private object _dataItem;
public object DataItem {
get { return _dataItem; }
set { _dataItem = value; }
}
public void Update(ref string t) {
t = "test";
}
}
public class Consume {
public void Example() {
CustomControl ctrl = new CustomControl();
ctrl.DataItem = anyObject.anyProperty;
string prop = anyObject.anyProperty;
ctrl.Update(ref prop);
anyObject.anyProperty = prop;
}
}
How can I change it so that the DataItem property is itself a reference, allowing you to pre-emptively set it to point to a variable thus allowing you to call Update() without any parameters.
So the Consume class would then look similar to;
public class Consume {
public void Example() {
CustomControl ctrl = new CustomControl();
ctrl.DataItem = anyObject.anyProperty;
ctrl.Update();
// anyObject.anyProperty has been updated to "test"
}
}
So the assigment of anyObject.anyProperty is then handled internally within CustomControl
You need to store the act of setting something to a string, so store an
Action<string>:Then
Consumewould look like:The
Updatecall will setanyObject.anyPropertytotest. Note that you are storing specifically the act of setting this property of the particularanyObjectyou refer to in the assignment toSetData.To expand on the lambda: we want to create a value of type
Action<string>, that is, a thing which takes astringand returns no result. Such a thing is going to be executable code. Prior to C# 3, to create a ‘value’ that was executable code, we would have had to do something like:With this syntax it’s more obvious that we’re creating a method – it has a
{ }delimited body, it has statements in it, and it’s clear there is a string parameter that is used by the body.One thing achieved by lambda expressions in C# 3 is the ability to condense this down; loosely, the whole of
can be replaced with
and in the case where there’s only one parameter
which is what we have here: the expression assigned to
ctrl.SetDatais a piece of behaviour that accepts a string (s) and setsanyObject.anyPropertyto that string. The real power is in the way the C# compiler can work out the types to it know we’re creating anAction<string>.