2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-01-27 13:42:22 +01:00
There are several compilations options available for Visual Basic source code and ``++Option Explicit++`` defines compiler behavior for implicit variable declarations. Specifying ``++Option Explicit Off++`` will allow creating a variable by it's first usage. This behavior can lead to unexpected runtime errors due to typos in variable names.
2021-01-26 04:07:35 +00:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
``++Option Explicit++`` can be set in project properties or overridden in individual source files.
2021-01-26 04:07:35 +00:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-01-26 04:07:35 +00:00
2022-02-04 17:28:24 +01:00
[source,text]
2021-01-26 04:07:35 +00:00
----
Option Explicit Off ' Noncompliant
Module MainMod
Public Sub DoSomething(First As String, Second As String)
Parameter = Fist ' New local variable "Fist" is created and assigned to new local variable "Parameter" instead of "First" argument.
DoSomething(Parameter)
Parametr = Second ' "Second" argument is assigned to newly created variable "Parametr" instead of intended "Parameter".
DoSomething(Parameter) ' Value of "Parameter" is always Nothing
End Sub
Private Sub DoSomething(Parameter As String)
' ...
End Sub
End Module
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-01-26 04:07:35 +00:00
2022-02-04 17:28:24 +01:00
[source,text]
2021-01-26 04:07:35 +00:00
----
Option Explicit On
Module MainMod
Public Sub DoSomething(First As String, Second As String)
Dim Parameter As String = First
DoSomething(Parameter)
Parameter = Second
DoSomething(Parameter)
End Sub
Private Sub DoSomething(Parameter As String)
' ...
End Sub
End Module
----
2023-05-03 11:06:20 +02:00
== Resources
2021-01-26 04:07:35 +00:00
2021-01-26 14:09:01 +01:00
* https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-explicit-statement[Visual Basic documentation - Option Explicit Statement]
2021-01-26 04:07:35 +00:00