If you have a variable of a reference type, you can either assign it an existing object
b = a; // Where a is another variable.
or assign it a newly created object
b = new A(); // Where A is a type.
or assign it null
. null
is the only pre-existing constant value of reference types (except for strings).
b = null;
new
makes it clear that a new object is created. This also runs the constructor. Whether it is on the heap or the stack is not important. Strings are treated in a special way in C#. Even though they are reference types, they have a value type semantic as they are immutable and have constants (literals) much like value types. You can create them with new
so, when you want to convert character arrays to strings, for instance.
A variable of a reference type always contains a reference or null
. It means that it always occupies the same amount of memory (either 32-bits or 64 bits, depending on OS and process type).
On the other hand, when you have a value type, you are either assigning a constant value (which has not to be created).
x = 5;
or you are assigning a copy of another value
x = t;
Note that structs are value types as well. If you want their constructor to run, you must create them with new
as well.
p = new Point(1, 2);
But struct fields or elements of struct arrays exist without having been created with new
. All their fields and properties are initialized to default values automatically.
var points = new Point[10];
creates ten points with coordinates (0, 0). The constructor of the single points is never called.