C#: How to get a return value from an Action

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.

 
Comments

Why not just use a Func?

You certainly could and it might be the better route considering it was designed with that concept in mind. I was directly addressing the desire to get a result from an Action; which generally doesn’t support this concept. If anything, it is a good exercise in understanding object referencing.

I like what you guys tend to be up too. This sort of clever work and coverage!
Keep up the superb works guys I’ve included you guys to our blogroll.

Leave a Reply