The Question:
Can I actually get a return value from an Action?
In my travels during research and development efforts on exciting coding projects I have seen this question get asked time and time again. The answers I usually see are:
– No, or
– Create your own Action object.
I think the point is missed here. The issue with passing a simple object into an Action and then setting your method result to that object, is that the object gets overwritten. Why? Because it’s an object. Once you assign something else to that object, the reference is changed. Therefore the original object is no longer in context.
How can we resolve this? We can easily do this with a complex object.
Our object:
public class MyComplexObject { /// <summary> /// Name provided for the result. /// </summary> public string Name { get; set; } /// <summary> /// Value of the result. /// </summary> public object Value { get; set; } }
Now, let’s add this to a new Action of type MyComplexObject:
Action<MyComplexObject> myAction = (MyComplexObject result) => { result.Value = MyMethodThatReturnsSomething(); };
If you reference your MyComplexObject, you will be able to use the value assigned to it’s “Value” property.
I know this isn’t Earth-shaking, but I hope this tip helps you along the way.
Happy Coding.
Why not just use a Func?