RnR
RnR

Reputation: 2115

How can I modify a value type variable passed to a lambda in C#

I'm writing some simple code to user initialize objects returned from a pool.

I though I'd use an Action to do this on the Pool side and pass a simple Lambda expression as a parameter to define that initialization.

To make this work I need to pass the variables to the lambda by reference and I can't find a way to do this for value types (such as int or a Vector3 in Unity3D).

Is it possible to pass them by reference and if not then what is my next best option?

My unit test code for this is (let's ignore the problem of checking floating point numbers for direct equality :) ):

pool.SetObjectInitializer(
            (objectInPool) => { 
                objectInPool.x = 1.0f; 
                objectInPool.y = 1.0f; 
                objectInPool.z = 1.0f; });

Vector3 objectFromPool = pool.Get();
Assert.AreEqual(new Vector3(1, 1, 1), objectFromPool);

Upvotes: 1

Views: 610

Answers (1)

Servy
Servy

Reputation: 203842

Action an Func don't pass any of their parameters by reference in any of the overloads. To have a delegate that has the signature that you want you'll need to create your own:

public delegate void RefAction<T>(ref T param);

Upvotes: 1

Related Questions