0

I just compile simple code in release mode both in Web Api and Console Application and I got different results

Web Api

var builder = WebApplication.CreateBuilder(args);

WeatherForecast _weatherForecast = new WeatherForecast();
_weatherForecast = null;

builder.Services.AddControllers();

Console Application

WeatherForecast weatherForecast = new WeatherForecast();
weatherForecast = null;

Then I just inspected those dlls using ILSpy tool and saw completely different result. For console application Jit compiler removed weatherForecast = null but for web api it remains. So it means that in console application does not make sense to set reference type variable to null to make some help for GC in advance

west
  • 346
  • 1
  • 5
  • 18
  • Why [set to null](https://stackoverflow.com/questions/49950/garbage-collection-is-it-necessary-to-set-large-objects-to-null-in-a-dispose-me) rather than use Dispose? See also https://stackoverflow.com/questions/2785/setting-objects-to-null-nothing-after-use-in-net – gunr2171 May 13 '23 at 23:14
  • sure, but wanted to focus you attention such behavior of CLR – west May 13 '23 at 23:20
  • 1
    Why are you setting what is obviously a local variable to null immediately after initializing it. The JIT compiler could, if it felt particularly optimizing-ish, could simply remove all reference to that variable (since it wouldn't affect the external behavior of the program). Once you are done with a local variable , just forget about it. If the compiler decides it's important, it will compile in hints to the JITter saying that a local variable is eligible for collection before it goes out of scope (if that won't affect the external behavior of the code – Flydog57 May 14 '23 at 03:56
  • @Flydog57 yes, you are right, I found out local variables that are set to null, they are cleaned out by JIT Compiler, but only in console application, and not in web api. I mean if I declare reference type variable in function and after a while set it to null it still remains in web api but not in consolo app – west May 14 '23 at 08:00

0 Answers0