I was just wondering if there is any difference between the two different new object initializers or is it just syntactic sugar.
So is:
Dim _StreamReader as New Streamreader(mystream)
and different to:
Dim _StreamReader as Streamreader = new streamreader(mystream)
Is there any difference under the hood? or are they both the same? Which one do you prefer to use?
The major difference is that Object. Create returns the new object while the constructor function return the constructor of the object or the object. This is due to the important difference that new actually runs constructor code, whereas Object. create will not execute the constructor code.
Using new Object() allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code: var obj1 = new Object(); obj1. a = 1; var obj2 = new Object(obj1); obj2.
create() is factory construction. You are delegating new() to the factory - the factory looks for overrides and replaces construction of your class with some other derived class. You should always use create() rather than using new() for classes registered with the factory.
Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.
In VB.NET, they're identical. The As New
variant is canonical.
In VB6, their semantics actually differed (apart form the obvious fact that VB6 didn't allow assignments in declarations): the As New
variant would create an object that could never be Nothing
. Rather, the runtime would ensure that the object was always properly initialized before each access to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With