Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between A a =new A() and A a=null

Tags:

heap-memory

c#

In C#,

A a = new A();
A a = null;
A a;

How does these 3 lines work with respect to memory?

I know the first line will create a memory in heap, but what about rest two lines?

How it work if, A a ; is a field and local variable.

like image 763
keerti_h Avatar asked Mar 14 '23 04:03

keerti_h


1 Answers

  1. Creates a new instance of A and assigns it to the variable a.
  2. Does nothing. It just assigns null to a reference a. If a is not used, the compiler might optimize it away.
  3. Does nothing too. It will revert to A a = default(A); which is the same as 2 since default(A) is null. For method variables it will show you a warning or error if you don't assign it. This one can too be optimized away if not used.
like image 148
Patrick Hofman Avatar answered Mar 24 '23 02:03

Patrick Hofman