Home
VB.NET
Const Keyword
Updated Sep 24, 2022
Dot Net Perls
Const. A Const variable cannot be changed. It is immutable. In the VB.NET language, Strings (and other types) can be decorated with the Const keyword.
Const types. Value types such as Integer may also be made constant. This influences performance. Const values resolve faster than regular variables. They should be used when possible.
Integer
This program uses a Const at the level of the Module: the syntax here is similar to a field. It also uses a Const at the level of the method: the syntax resembles a local variable Dim.
And The const identifiers "_x" and "name" can be referenced in the same way as variable identifiers.
But You cannot reassign a const. This provokes a compile-time error—the program will not compile.
Module Module1 ''' <summary> ''' Const can be Module or Class level. ''' </summary> Const _x As Integer = 1000 Sub Main() ' Const can be Function or Sub level. Const name As String = "Sam" ' Used as an argument. Console.WriteLine(name) Console.WriteLine(_x) ' Constant cannot be the target of an assignment. '_x = 2000 End Sub End Module
Sam 1000
Performance. Fields and variables—declared with Dim—designate memory locations. When a Dim variable is evaluated, the execution engine reads from that memory location.
But With Const, the compiler inserts the value directly into the intermediate language representation.
So This means that when the method is executed, the value does not require a separate memory access. This slightly improves performance.
Summary. Const values help clear up confusing code. With Const we construct self-documenting code. A Const with the identifier "name" is known to be a name by any programmer reading the code.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 24, 2022 (rewrite).
Home
Changes
© 2007-2025 Sam Allen