Does VB.NET have an empty statement? - vb.net

I am looking for an empty statement in VB.NET similar to this in C/C++:
;
My understanding is this is simply an empty statement that does nothing. However, when I try to use a C# to VB.NET converter to gain some insight I am just given a blank line. Is there something similar I can use besides empty space?

When I have to do a do-nothing line in VB.NET just like "pass" in Python, I use the following one liners:
The "Just 8-bits Used"
Dim i As Byte = 0
"The Shortest One"
Dim i = 0
The "No Memory Used"
If 1 <> 1 Then Dim i = 0
I suggest you to add a "TODO / HACK / UNDONE" comment so you can remember this line it's just a placeholder line and you can find it easily in your task list. Example:
' TODO: Add function logic
Dim i = 0
More info about Creating task list comments HERE

In C an expression becomes a statement when it is followed by a semicolon. The semicolon itself is just a statement terminator. The equivalent to a statement terminator in Visual Basic is a line break and the equivalent of an empty statement is an empty expression followed by a line break.
Your first example would look something like this.
Function ProcessMessage() As Boolean
...
End Function
Sub ProcessMessages()
While ProcessMessage()
End While
End Sub
Your second example would look something like this. Note however that exit is a keyword in Visual Basic, so we have to call the label something else.
Sub f()
...
If done Then
GoTo _exit
End If
...
_exit:
End Sub

VB.Net does not have an empty statement, but you can easily add one (tested with .net 6.0):
Imports System.Runtime.CompilerServices
public Module VbExtras
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Sub NextSentence() : End Sub
End Module
...
Public Class C1
Public function Method1() as Boolean
If l > 0 Then
If b IsNot Nothing Then NextSentence '' useful for precompiler work
Else
Console.WriteLine("filled")
End If
return False
End Function
End Class

Related

Set a Property Value From Database of Properties

My database has the formname, control, and control property type value stored.
I would like to have a line of code like this.
Forms(i%).Controls(ControlName$)).controlpropertytype$ = NewValue
I am currently using a select case structure to handle the various property types. It would be much simpler to have a single statement take care of it.
Using a helper function, you can achieve this with one line of code. Here's an example of setting a TextBox on Form1 to the value 'aaa':
Option Explicit
Private Sub Test()
CallByName FindForm("Form1").Controls("Text1"), "Text", VbLet, "aaa"
End Sub
Public Function FindForm(ByVal Name As String) As Form
Dim f As Form
For Each f In Forms
If UCase(f.Name) = UCase(Name) Then
Set FindForm = f
Exit Function
End If
Next
End Function
While this is an interesting exercise, I would not recommend this approach. It assumes the form and the control can both be found, but if they can't be found this one-liner will crash your app.
Here's documentation for CallByName.

Call Function when User Types Certain Keyword

Okay, so I am working on a small scripting language using a VB Console Application.
I want the user to input "say('something')" and it calls the function I made named "say", is there a way to call the function and still use the following code:
Module Module1
Sub say(sayline)
Console.WriteLine(sayline)
End Sub
Sub Main()
Dim cmd As String
Console.WriteLine(">")
Do
Console.Write("")
cmd = Console.ReadLine()
If cmd IsNot Nothing Then cmd
Loop While cmd IsNot Nothing
End Sub
End Module
No, you cannot just call a method from user's string. You need to interpret the entered data.
First, you need to split your method name and arguments so that entered "say('something')" will transform to say and something. Remember that user can enter wrong data and you need to check if this call is correct - it's all about syntactic and lexical analysis. I hope you understand how to do this because it is pretty difficult.
Then, you need to check if you have a method called say. In case of plain and simple structure, switch construction will be enough. If your have such method, then pass something argument to this method. Else, output something like "unknown method".
If you wanted to call the method say upon typing the word say(something) and display the word something, then you can just have a certain condition that if the user types the word say within the input then call say method else, do whatever you want to do under else portion. Parse the input and omit the word say from the input and display it then.
You can have your code this way for example. (I just copied your code and added some codes to meet what you wanted... in my understanding)
Module Module1
Sub say(ByVal sayline)
Console.WriteLine(sayline)
End Sub
Sub Main()
Dim cmd As String
Do
Console.Write("> ")
cmd = Console.ReadLine()
Try
If cmd IsNot Nothing And cmd.Substring(0, 3).ToUpper().Equals("SAY") Then
say(parseInput(cmd))
End If
Catch ex As Exception
Console.WriteLine("message here")
End Try
Loop While cmd IsNot Nothing
End Sub
Function parseInput(ByVal cmd As String) As String
Dim input As String = ""
For index As Integer = 3 To cmd.Length - 1
If Char.IsLetter(cmd) Then
input += cmd.Substring(index, 1)
Else
input = input
End If
Next
Return input
End Function
End Module

Variable declaration with Nothing check

Very (very) often we need to write stuff like
Dim Data = GetSomeData()
If Data IsNot Nothing Then
Data.DoSomething()
Else
...
End If
Maybe I am asking in vain but I am seriously hoping that VB.Net has some construct like:
IfExists Data = GetSomeData() Then
Data.DoSomething()
Else
...
End IfExists
In my dreams it does two important things:
No extra line for Nothing check
Variable A is not visible outside of the block and thus can't be used later on by mistake (just like "Using" or "With")
Is there anything similar to that that I haven't found yet?
Thanks!
EDIT:
Inspired by Bjørn-Roger Kringsjå's Answer I came up with something that would satisfy me (humbled by VB.Net's deficiencies):
<Extension()>
Public Sub IfExists(Of T)(This As T, DoIfNotNothing As Action(Of T), Optional DoIfNothing As Action = Nothing)
If This IsNot Nothing Then
DoIfNotNothing(This)
ElseIf DoIfNothing IsNot Nothing Then
DoIfNothing()
End If
End Sub
Then I can call it like this (with the false part being optional)
GetSomeData().IfExists(Sub(Data) Data.DoSomething())
or
GetSomeData().IfExists(Sub(Data) Data.DoSomething(), Sub() DoSomethingElse())
As stated by others and implied by me, it can't be done. Just like to share a 3'rd solution. This time we're going to use delegates.
No extra line for Nothing check
Variable A is not visible outside of the block and thus can't be used later on by mistake.
Implementation
Public Module Extensions
Public Sub IfExists(Of T)(testExpr As T, trueDlg As Action(Of T), falseDlg As Action)
If (Not testExpr Is Nothing) Then
trueDlg.DynamicInvoke(New Object(0) {testExpr})
Else
falseDlg.DynamicInvoke(New Object(-1) {})
End If
End Sub
End Module
Usage
IfExists(GetSomeData(),
Sub(A As Object)
'We have something (A)
End Sub,
Sub()
'We have nothing
End Sub
)
Shorter:
IfExists(GetSomeData(), Sub(A As Object)
'We have something (A)
End Sub, Sub()
'We have nothing
End Sub)
Or, the shortest version:
IfExists(GetSomeData(), Sub(A As Object) Debug.WriteLine(A.ToString()), Sub() Debug.WriteLine("Nothing"))
No, unfortunately there is nothing like that currently in VB.NET. The closest thing you could do to approximate that behavior would be to write a function like this:
Public Function Assign(ByRef target As Object, value As Object) As Boolean
target = value
Return (target IsNot Nothing)
End Function
Then you could use it like this:
Dim A As SomeType
If Assign(A, GetSomeData()) Then
' ...
Else
' ...
End If
But, as you pointed out, that doesn't really solve either of your stated problems. It's still an extra line of code, and the variable is still not scoped to only be accessible within the block where it was properly assigned.
The first point is not possible. There is no way to declare a variable and check it in a single statement.
The second point is sort of possible. Creating your own block scope is not supported by VB.NET, but you can achieve it by abusing other blocks. Insert your code within a single-use Loop While block:
Do
Dim A = GetSomeData()
If A IsNot Nothing Then
...
Else
...
End If
Loop While False
The Do block will be entered, with A declared local to that block, then the block will immediately exit at While False, and A will no longer be accessible.
A probably better way to simplify this is by restructuring the code into more, smaller methods so that the If ... Else is the entire method and there is no possibility of accidentally accessing an outdated variable later. When you do this, you can also exit early from the method in the simpler case instead of keeping both If and Else branches:
Dim A = GetSomeData()
If A Is Nothing Then
...
Exit Sub
End If
...
End Sub

VBA Excel "Variables are required"

Got a trouble in a VBA excel program.
Sub code(s)
...
code = t
End Sub
And then :
Sub CommandButton1_Click()
...
For i = 0 To size
current_y = code(string_array(i))
...
End Sub
When i run the program, i got this error "Variables are required" (not sure, i'm working on a japanese version of excel). Sub CommandButton1_Click is highlighted and code is selected inside CommandButton1_Click. Can't figure out why, though it must be simple...
You're trying to return a result from a Sub. Try declaring it as a function instead, as this is able to return values to the caller:
Function code(s)
...
code = t
End Function
If it makes it any clearer, on my English version the error message is:
Expected Function or variable
Does the code include Option Explicit? Perhaps the error translates to "Variable declaration required"? Try removing option explicit - if that fixes it remove that line, then go through checking all variables are declare (e.g. dim current_y as string).

Why does my function's name appear twice in the "locals" window?

I have created a Class Module in which I have defined a function. Whenever that function is called, it is listed twice in the locals window. Only the second one's value changes, the first one stays either empty or "zero", depending on its type, until the end of the code's execution. I don't have this problem with functions defined in standard modules. Did I do something wrong, is this a bug, or is there a logical reason behind this?
Contents of the TestClass class module:
Public Value As Double
Function AddFive() As Double
AddFive = Me.Value + 5
End Function
Contents of the standard module:
Sub TestSub()
Dim TestObject As New TestClass
TestObject.Value = 2
MsgBox TestObject.AddFive
End Sub
Here is a screenshot showing that, when the code is executed line-by-line, the function's value is listed twice in the locals window, and only the second value has changed after the function's code was executed.
(link to screenshot)
I'm using VBA for Excel 2010.
Thanks in advance.
The issue is more in how you are doing it. If you have a function that just adds 5 to an internal variable of a class object, then it's technically a void (Sub in VBA) since you don't need a return value.
Your code should be:
CLASS
Public Value As Double
Sub AddFive()
Me.Value = Me.Value + 5
End Sub
MODULE
Sub test()
Dim testObject As New TestClass
testObject.Value = 2
testObject.AddFive
MsgBox testObject.Value
End Sub
I can imagine there could be a number of reasons why there are 2 variables created, but I find it a bit pointless to go into why there is unexpected behavior since you are doing improper code.
If you want, you can even write class function that will show it's value + 5 in a msgbox and this would not create an extra variable either. But that is strange and I think you want the code above. But here it is regardless:
CLASS
Public Value As Double
Sub ShowPlusFive()
MsgBox Me.Value + 5
End Sub
MODULE
Sub test()
Dim testObject As New TestClass
testObject.Value = 2
testObject.ShowPlusFive
End Sub