As New FolderItem vs As FolderItem

In the Documentation, I see

Var f As FolderItem

and

Var f As New FolderItem

I am unclear as to when one might need the “New” and when not necessary.

That looks like an incomplete example. New FolderItem by itself is not very useful. Something like

var f as New FolderItem("c:\somedir\somefile.txt") 

is more common. It replaces the old syntax for creating a folderitem from a path.

1 Like

This example displays the native path:

Var f As New FolderItem
 MessageBox(f.NativePath)

This is from the Documentation and it would seem that in this case the New Folder line, although not explicitly stated, is equivalent to

Var f As New FolderItem("")

The below will result in an error.

Var f As FolderItem
 MessageBox(f.NativePath)

When I was scanning the Documentation I saw things like this that confused me, but after Tim’s response I can see the theme of New FolderItem being in a context of creating a FolderItem from a path.

Either

Var f As FolderItem
f = New FolderItem("myDoc.txt")

Or

Var f As New FolderItem("Zippy.png")

The below is fine because you are not creating the FolderItem from a path.

Var f As FolderItem = SpecialFolder.Desktop.Child("test.txt")
Var f As FolderItem

simply defines f as being of type FolderItem. f is not currently initialized and doesn’t point to any FolderItem object (it’s Nil).

Using the “New” keyword initializes the FolderItem class and calls its Constructor, which as you and Tim pointed out, accepts a string parameter to convert/return a FolderItem instance pointing to a file with that string as NativePath.

2 Likes
Var v1 As Integer           // Define the container for a Integer
Var v2 As Integer = value   // Define the container for a Integer and put a value there

Var f1 As FolderItem        // Just a container for a future FolderItem object
f1 = New FolderItem         // create a FolderItem object and put in there

Var f2 As New FolderItem    // Define the container, create the object, and put in there

1 Like

similar to SpecialFolder. which return a object

you could write
Var f As FolderItem = MyFile()

Method MyFile()
  return New FolderItem("myDoc.txt")

Distinguish between types such as Integer, Double, String where declaring a variable of that type inherently also allocates the space to put it in. This differs from when you declare Var to be of type such as dictionary, folderitem etc, because these are objects, and declaring such a type does not create the object - so they initalise to Nil. You need to use the New keword to have the object created:

Var  x as Dictionary       // x will be born with a Nil value
x = new Dictionary         // A dictionary object is created and x now points to it.
1 Like

And don’t start mentioning arrays (which are objects under the hood, and can be nil in unusual circumstances), but aren’t declared with “new” :wink:

1 Like

but aren’t declared with “new”

or TextOutputStream used .Create or .Open
and Color is bit special