When to use 'As New' to declare an object

R

Ritu

I am just migrating from ASP and VB to .NET and what
confuses me the most is what is an Object and what is not.
Most Data Types (even the basic ones) are treated like
objects and have functions associated with them. However,
we do not instantiate all of them using an 'As New' as was
the norm earlier.

This might sound like a silly question, but could someone
thrash out this basic concept for me please.

Thanks in Advance
Ritu
 
M

Marina

The primitive types are value types (aka structures). This means that all
their members get initialized to default values when the object is declared,
thus there is no need to call new to create an instance. There other
behaviors that are different, such as:
Dim i as Integer = 2
Dim j as Integer
j=i

j and i are pointing to different instances of the Integer structure - they
both hold the value '2'. Something like this:
Dim i as New SqlConnection()
Dim j as SqlConnection
j = i

Now, j and i are pointing to the exact same instance of SqlConnection in
memory. Because SqlConnection is a reference type, not a value type, New
had to be used to initialize an instance. Otherwise the reference would be
pointing to nothing.
 
S

Steve C. Orr, MCSD

It still works mostly the same as always.
The main difference, as you've discovered, is that everything basically acts
as an object now. This is very handy.
But underneath it all you still have value types and reference types.
Integers and Bytes and things are still value types so you don't need to
explicitly instantiate them.
Most other object types need to be instantiated, unless the object's methods
are declared as shared (static in C#).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top