Why can we skip New keyword for MemoryBlock Class?

Oh careful! You are running into a self-made explanation that misses the point completely.

Technically, what is done when you write something like

Var myObject As aClass

is that there is just space for one pointer being reserved (8 Bytes on 64 bit systems) and that variable gets marked as its class type. Nothing else. No additional RAM for the object information itself is being reserved nor initialised. The constructor is meant for the latter: Create an object from scratch. Reserve additional RAM for the object properties. Run other set-up-code.

If in your example you write

Var mb As MemoryBlock

and you try to use it by addressing say mb.Uint8Value(0) you will get a NilObjectException because there is just one uninitialised object being addressed.
Only using an object constructor enables you to use an object you created on your own.

A line like
mb = s
causes Xojo to convert the string content (standardly UTF8-, not ASCII-encoded) into a Memoryblock. So behind the scenes mb will be initialized by Xojo.

You do not have to (better read that: You should not) initialize an object just as a container for an object that will be returned from another method. Initialization costs time and is not necessary where you receive a valid object. That’s why

is wrong. The second line will only throw an exception when you try to address the variable’s content (seen by itself. Using the same name twice will of course cause an error as Markus depicted.). By itself it will not cause any error.

If you have a method that returns an initialized object, you do not have run the constructor of the variable you want to put that object into. Something like

Var dog As Animal = myZoo.ReturnAnimalforWalking

could be fully ok. Just like Memoryblock.

Does that clarify things a bit?

2 Likes

Also see this doc topic which might help further clarify the difference between the class, the reference and the instance:

https://documentation.xojo.com/getting_started/object-oriented_programming/oop_classes.html

1 Like