Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

The "new" keyword

Status
Not open for further replies.

taubate

Programmer
Jun 29, 2001
141
US
Obviously, when it comes to simple value types like int, "new" is not needed. But I have noticed that the "new" keyword is not used in other, not-so-obvious cases (e.g. DataColumn).

How can I determine if the "new" needs to be used? Thanks!
 
"new" is required when instantiating a reference type yourself. There are certain objects (like you've seen) that act as class factories and return you an instantiated object.

The best way to determine if you need to call it or not is to use the online help. If the object has a constructor listed you're probably OK to instantiate it yourself. But it always pays to look around at related classes to see if a method on one of them will return you an instance.

Chip H.
 
So, a general rule of thumb is that if an objector has a constrcutor, use "new"; if not, "new" is probably not needed.

Am I right?
 
A public constructor, maybe. It still may be the case where the object is normally built by calling a method on another object.

A good example of this is the SqlParameter. It has four or five constructors, and you can call 'new' on it, but the usual way of creating one is to call the CreateParameter method of the SqlCommand object, which returns one to you.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top