Is it considered bad practice to use colons to put two statements on the same line in Visual Basic?
-
2I used to do it in vb6 to place the declaration and initialization on the same line, but that problem was fixed in vbn. – Craig Gidney Sep 15 '09 at 19:46
12 Answers
There is nothing inherently wrong with using the colon to combine statements. It really depends on the context but as long as it doesn't reduce readability, there is nothing wrong with it.
As a general rule I avoid using the colon for this purpose. I find it's more readable to have one statement per line. However this is not a colon specific issue. I avoid doing the same with a semi-colon in C# or C++. It's just a personal preference.

- 733,204
- 149
- 1,241
- 1,454
-
8+1 Agreed. I did VB for more than 10 years, and I didn't even *know* you could put statements on the same line separated by a semi-colon. I wouldn't do this unless the vertical scrollbars on my computer were broken. – MusiGenesis Sep 11 '09 at 15:50
It's a good practice in moderation, because sometimes readability is enhanced by concatenating two lines:
- when the lines are short and intimately related
when the lines are short and trivial
Option Compare Database: Option Explicit ''My favorite! rsDataSet.Close: Set rsDataSet= Nothing
Don't do it if:
- it hurts readability.
- it complicates debugging. Control structures such as
If...Then
need to stay clean. You'll be glad you kept it simple when it's time to set a break point. - it compromises future editing. Often you want to keep sections portable. Moving or re-structuring a block of code is easily hindered by attempts to minimize your code.

- 6,919
- 3
- 49
- 83
In general, I'd advise against it, as it makes for busier code.
However, for simple tasks, there is nothing wrong with it. For instance:
for i = 1 to 10: ProcessFoo(i): next
I think a line like this is short enough not to cause confusion.

- 59,598
- 102
- 325
- 594
I'll take the other side. I don't like dense lines of code. It is easier to skim code when lines are not combined.
Combining statements also makes it easier to create long functions that still fit on a single screen.
It isn't a major sin, I just don't like it.
I also don't like one line If statements.

- 2,790
- 1
- 19
- 35
To me you shouldn't say "never do thus", you should just say "If you do this, a possible problem is such and such." Then just weigh the pros and cons for yourself. The pro is brevity/few lines of code. Sometimes this can aid readability. For instance some people use it to do vb.Net declarations:
Dim x As Long: x = 1
Or wait loops:
Do Until IE.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
But obviously you can really make it rough on someone too:
Public Sub DoYouKnowWhatThisDoes()
MsgBox Example
End Sub
Private Function Example()
Const s$ = "078243185105164060193114247147243200250160004134202029132090174000215255134164128142"
Const w% = 3: Const l% = 42: Dim i%, r$: For i = 1 To l Step w: r = r & ChrW$(Mid$(s, i, w) Xor Mid$(s, i + l, w)): Next: Example = r
End Function
Another practical reason that you might not want to use this approach is breakpoints. Breakpoints can only be set by the line. So if you have several things executing on the same line you can't isolate the second thing. It will stop on the first statement. (This is also one of the reasons some people don't like single line ifs.) It just complicates debugging a little.
I usually don't use colons in production code for this reason. However I do use them to improve the brevity of "copy/paste" code that I post in forums and elsewhere. YMMV:)

- 6,630
- 1
- 35
- 52
I realize this is a very old question, but it was the first result on my Google search, so I hope I can be forgiven for chiming in here.
There is one situation (exactly what led me here in fact) in which this approach is not only useful, it's the only way to accomplish the desired result: the Immediate window. Any code you want to execute in the Immediate window must all be on one line. So in order to use any form of Do, Case, For, While, or With in the Immediate window, you will need to use colons.

- 523
- 7
- 10
-
1Again old question, but since this is a new answer I'll post a new comment. I rarely use the `:` in code but I found that it was very useful in dealing with this bug: http://support.microsoft.com/kb/327244 I used the `:` in the following way: `Me.ComboBox.SelectedItem = Nothing : Me.ComboBox.SelectedItem = Nothing` I could have put that on two lines, but it made it simpler to read all on one line and it made sense since it was just a repeated statement. – вʀaᴎᴅᴏƞ вєнᴎєƞ Jan 26 '15 at 14:19
It is considered bad practice in most of the sites at which I have worked. And by most of the VB developers with whom I have worked. And in my head. If I see it, I will admit that I would almost certainly change it. I say "almost" because I admit there's a possibility that I could find a piece of code that looked better that way. I don't expect to see it in my lifetime, though.
I also really don't like one-line **If
**s either.
Both are most likely hangovers from the days of VGA (640x480) monitors; that's no excuse these days.

- 51,832
- 12
- 88
- 127
I've only ever used it when I'm clsoing a recordset and setting the variable to nothing. I figure one line instead of two gives me more lines of code on the screen and doesn't detract from readability.
I've seen it used in simple select cases such as the following but that would be as far as I would go.
Select Case success
Case ERROR_FILE_NO_ASSOCIATION: msg = "no association"
Case ERROR_FILE_NOT_FOUND: msg = "file not found"
Case ERROR_PATH_NOT_FOUND: msg = "path not found"
Case ERROR_BAD_FORMAT: msg = "bad format"
from http://vbnet.mvps.org/index.html?code/system/findexecutable.htm
And even then I would've lined up the "msg =" portion.

- 7,850
- 1
- 22
- 27
-
2Do ever think of the person who will inherit your code? Have you considered that I cannot place a breakpoint in the VBE IDE on the line msg = "no association" without causing break mode in *every* case? – onedaywhen Sep 14 '09 at 12:56
-
2Your comment is irrelevant in the only two cases I've ever place two staements on the same line. – Tony Toews Sep 14 '09 at 18:47
-
1
-
2
-
1What have we disagreed about? You placing two statements on the same line would mean that I cannot put a breakpoint on the second statement. Isn't that unequivocal? – onedaywhen Sep 16 '09 at 07:30
-
1So what. You'd never put a breakpoint on a simple Select Case like that. – Tony Toews Sep 16 '09 at 08:54
-
1What if a defect had been reported that the message "no association" was showing unexpectedly. A search through the code reveals but one instance of that phrase. So I'd want to set a breakpoint on that line. See what I mean? – onedaywhen Sep 16 '09 at 09:02
-
1BTW I have to do put break points on Case statements quite often when maintaining legacy VBA code, so this a practical point born out of experience of working with other developers, some of who like single line statements. – onedaywhen Sep 16 '09 at 09:07
-
4Your objections are exceedingly strenuous for such a minor point. But do what you like. – Tony Toews Sep 16 '09 at 19:25
-
I know this is old, but if I needed to debug that line as suggested, I'd just adjust the code with a couple of keystrokes so that the assignment was on another line and then place the breakpoint there. Or use a conditional breakpoint. This doesn't seem like a big deal and tightening those case statements up, particularly when there are a lot of them is pretty valuable to reader-flow. – clweeks Dec 20 '18 at 16:05
I've never seen this mentioned in an official capacity at any of the companies which I've worked. But I do think that using colons excessively can start to make your code less readable and more of a pain to maintain.
I do tend to use these myself at times, for example when checking for cancel in one of my recent projects:
If _bCancel Then Status = CancelProcess() : Return Status
Putting this in kept my code readable than the alternative IF block.
But it can be taken too far, I've recently inherited a project which is replete with examples of taking colon usage too far :
Select Case GetStringValue(Index).Trim.ToLower
Case "yes", "y" : GetBooleanValue = True
Case "no", "n" : GetBooleanValue = False
Case Else : GetBooleanValue = Nothing
End Select
Personally I find the above to be a bit much.

- 555
- 1
- 7
- 16
-
2I think you could go worse, at least that fits on the screen as one line – Paul C Feb 04 '13 at 11:55
-
I like this one
Using pro As New Process() : With pro
...
End With
End Using

- 380
- 3
- 13
I've seen it used in class declarations when using inheritance or implementing an interface:
Public Class DerivedClass : Inherits BaseClass
...
End Class
But like the others, I also discourage its use.
Chris

- 10,974
- 4
- 36
- 48
-
1that's vb.net of course. And I think it has C# envy, which is why Inherits is on the same line as the Class – MarkJ Sep 12 '09 at 08:19
The answer to the question is No. Anything beyond No is purely subjective and wasteful irrespective of the answer outside of a simple No. Below is my waste of typing.
Are you some sort of slave? Do as you wish. You are the center of your universe not some stranger from StackOverflow. If you work for a company the question is mute because coding style would already be defined and completely out of your control. As for one's self, who in this universe is going to ever in all eternity look at let along care about your code.
I would choose A over B. As evident this shows the purpose of a colon without the use of a colon. It's to save space. Below saves space and makes code far more readable. Keeps It Simple Stupid. Same for ternary ? : usage. When the code is inherently complex then a colon, single line if then else, or ternary no longer should be considered.
'================================================================
'A
If somevalue1 = 0 Then AddLogTry("True") Else AddLogFalse("False")
If somevalue2 = 0 Then AddLogTry("True") Else AddLogFalse("False")
If somevalue3 = 0 Then AddLogTry("True") Else AddLogFalse("False")
'================================================================
'================================================================
'B
If somevlaue1 = 0 Then
AddLogTrue("True")
Else
AddLogFalse("False")
EndIf
If somevlaue2 = 0 Then
AddLogTrue("True")
Else
AddLogFalse("False")
EndIf
If somevlaue3 = 0 Then
AddLogTrue("True")
Else
AddLogFalse("False")
EndIf
'================================================================