Search code examples
c#unity-game-enginejetbrains-iderider

Delegate allocation: capture of 'this' reference in JetBrains Rider


When I was doing my code in C# I found a yellow line below arrow function as shown in image, I hovered my cursor over it and it showed

"Delegate allocation: capture of 'this' reference"

I searched this on google but didn't find anything.

enter image description here

I also found that when I remove initRemoteConfig field than that line goes away.

So can anybody explain what's happening here and what to do to remove this warning?


Solution

  • This is about lambda capturing outer context (docs about capturing a local variable, or there are some answers about this on SO). It seems that initRemoteConfig is a field/property on class containing this code, so your lambda needs to capture current instance of this class.

    Also this is not a build in rider inspection it comes from heap allocations viewer which helps you to prevent unnecessary allocations, but sometimes you still need to allocate, so you can't always fix this warnings (i.e. this plugin will always "warn" about any allocation and it is up to you to decide if it is necessary or not). In this particular case, if it is suitable for your context, you can make the initRemoteConfig property/field a static one, i.e. something like this:

    private static int initRemoteConfig;
    Action x = () =>
    {
        initRemoteConfig = 3;
    };
    

    will not give you this warning (but has some other drawbacks).