Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Strictly speaking, it depends on where the code is.</p> <p>If the code is in a regular function/method, it will affect the stack only. There will be no effect on the heap, because no MyClass objects have been constructed yet.</p> <p>Assuming MyClass is a class (i.e. reference type), the declarations will each reserve enough space on the stack to hold a reference to a MyClass object.</p> <p>The two declarations are slightly different - the first one has not been initialised, so any attempt to access oMyClass1 before it is set to something will give a compiler error. The second one is initialised, so you will not get a compiler error [although you will get a runtime error if you access a method or property of oMyClass2 before you set it to refer to an actual object, e.g. with oMyClass2 = new MyClass();].</p> <p>If the code is inside a class declaration:</p> <pre><code>class Fred { MyClass oMyClass1; MyClass oMyClass2 = null; } </code></pre> <p>then it will only be executed during the Fred constructor. The space (for a Fred object, including space for two MyClass references) will already have been allocated on the heap before the constructor is called. The two lines of code will actually have no effect, as the space will already have been initialised to null.</p> <p>If it is inside a struct declaration, the effect will be similar, only on the stack (if the struct is local) or global variable memory (if the struct is static). [Although, to be fair, I'm a tiny bit unsure where statics get allocated in C# - I am just assuming it is done in a similar way to C++]</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload