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!

How do I know when to use keyword 'New'?

Status
Not open for further replies.

Bullfrog1870

Technical User
Dec 26, 2005
15
US
I still don't understand when to use the keyword New and when not to, when declaring an object.

Example: System.IO.Directory does not require a New keyword to create a variable. However, System.IO.DirectoryInfo does require New for a new variable.

How do I know this? Other than trial-n-error, or asking explicitely, how do I know?

strPath = System.IO.Directory.GetCurrentDirectory()
myDirectory = New System.IO.DirectoryInfo(.....)

Thanks!
 
New is used when you need to create an instance of an object. There are methods on an object that can be called without an instance, called shared (static in C#). This is what you're seeing on the Directory class.

How to know? If the method or property you want to access isnt' marked shared, then you'll need to create an instance with New.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Use the NEW keyword to create a new instance of a class, if and only if there is a (or more) constructors.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top