When to use “new” syntax in object creation

  • Thread starter Thread starter Jean Stax
  • Start date Start date
J

Jean Stax

Hi !

A couple of pretty basic questions:

Value types:

As far as I understand, when I create value type without "new" syntax
the object is considered as unutilized. Consequently, I have to
initialize its member variables manually; otherwise I would get an
exception while accessing them.
Does this means that the constructor of the object, which is created
without_new_way wouldn't be called?

Reference types:

Do I always create reference types with "new" syntax or there are some
cases when I create my object without "new" and it still will be
allocated in managed heap?

Thanks.

Jean.
 
Jean Stax said:
A couple of pretty basic questions:

Value types:

As far as I understand, when I create value type without "new" syntax
the object is considered as unutilized. Consequently, I have to
initialize its member variables manually; otherwise I would get an
exception while accessing them.
Does this means that the constructor of the object, which is created
without_new_way wouldn't be called?

Bear in mind that you can't define a parameterless constructor for a
value type, but you can always do new ValueType() as if there *was*
one. Other than how you initialize the member variables (and when the
value is considered to be initialized) I don't think there's any
difference between the two. I'd personally try to use a constructor
wherever possible.
Reference types:

Do I always create reference types with "new" syntax or there are some
cases when I create my object without "new" and it still will be
allocated in managed heap?

You can't create an object without a "new" being involved somewhere
(with a few possible exceptions like serialization - not sure) although
you may not call the "new" yourself (eg factory methods). *All*
reference type objects are allocated on the managed heap though.

Note that when you just *declare* a reference type variable, that
doesn't create an object at all - the variable's value is undefined if
it's local, and null if it's class/instance.
 
Back
Top