Question about Var/Dim

Quick question about syntax when working with classes and instances. Which do you prefer?

Dim objMyClass As clsMyClass = New clsMyClass


Dim objMyClass As New clsMyClass

The 1st syntax: 1) Creates a variable of type clsMyClass, 2) Creates a new instance of clsMyClass and assigns it to objMyClass
The 2nd syntax: 1) Creates a new instance of clsMyClass and assigns it to objMyClass (skipping the explicit defining of the variable type)

Does anyone here use the longer syntax? Or do you prefer the shorter syntax?


If I need a new instance, I will always dimension as new.

dim toThis as new clsMyClass

If I pull from a shared function (factory design) I’ll dimension and assign in the same line.

dim toRecord as DataFile.t_Customer = DataFile.t_Cusomter.FindByID(42)

If the line is super long, I’ll use multiple.

dim toUserPersonalDetail as DataFile.tx_CustomerDetail = _ DataFile.tx_CustomerDetail.LookByMultipleParams(4, 7, "theFace")

Additional Tim-isms:

  • I Never Write BuzzFeed Headline Code Because It’s Actually Harder To Read Fast. There’s A Reason We Don’t Read / Write All Sentences Like This So I Don’t Understand How Anyone Read/Writes Code Like This
  • I use dim because it works in all versions of the IDE. Var only works in newer ones, and I work with many different versions of Xojo.

2nd syntax is short and sweet and to the point. I see no point to the 1st version as it forces me to keep reading for code that is functionally the same thing.

I usually do the wrong thing anyway so either works for me :stuck_out_tongue:

The 2 are identical behind the scenes. The 2nd is just syntactic sugar for the 1st. I always use the 2nd.

Historically, I learned the second first.

The first syntax allows you to instantiate a subclass in a variable typed as a superclass.

Dim myobject As SuperClass If SomeCondition = True Then myobject = New Subclass1 Else myobject = New Subclass2 End If