When to use 'New' key word?

L

Learner

Hello,
I have a basic question regarding 'New' keyword.

For instance I can declare a variable as string (class)

as Dim myName as String = String.Empty
or Dim I as Integer
But when I want declare a button we instantiate it as
Dim b as Button = New Button

I am just trying to understand when (for what kind of classes) to use
New key word.

Please some one help to clarify this.
Thanks
-L
 
K

Karl Seguin [MVP]

There are two fundamental types of variables in .NET (and most any
language). IN .NET they are called Value types and Reference Types.
Technically value types are allocated on the stack (relatively small amount
of memory), reference type are allocated on the heap (relatively large
amount of memory).

Knowing that, you don't use "new" to instantiate any value types, and you
use it to instantiate reference types. Value types are all the primitive
types (int, char, bool, long) and structure (either that you create or
pre-existing ones (ints, chars, bools, longs,... are all structures)). All
other "classes" are instantiated with new. The exception is a string which
despite being a reference type doesn't require a new.

You can read up more on stack and heaps and get even greater insight.

Karl
 
P

Pipo

For classes you'll need to call the new keyword
For value-types (integer, double, string, etc) you dont have to do that.
Also for shared or static functions in a class you dont need to use new.

Hope this helps.
 
G

Guest

Use new when the IDE asks for it.

Pipo said:
For classes you'll need to call the new keyword
For value-types (integer, double, string, etc) you dont have to do that.
Also for shared or static functions in a class you dont need to use new.

Hope this helps.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top