I'm trying to save a timestamp into a constant at the beginning of a program's execution to be used throughout the program. For example:
Const TIME_STAMP = Format(Now(), "hhmm")
However, this code generates a compiler error - "Constant expression is required." Does that mean all constants in VB .NET have to contain flat, static, hard-coded data? I know that it's possible to initialize a constant with a dynamic value in other languages (such as Java) - what makes it a constant is that after the initial assignment you can no longer change it. Is there an equivalent in VB .NET?
The dynamic keyword in C# gave it that same capability. It did get changed in VB.NET version 10 however, it is now using the DLR as well. Which adds support for dynamic binding to language implementations like Python and Ruby. The syntax is exactly the same, use the Dim keyword without As.
The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only.
Use the const keyword in C# Variables declared using the const keyword are also known as compile-time constants. It should be noted that a constant variable is immutable, i.e., the value assigned to a constant variable cannot be changed later.
In VB.NET, const is a keyword that is used to declare a variable as constant. The Const statement can be used with module, structure, procedure, form, and class.
You need to make it Shared Readonly
instead of Const
- the latter only applies to compile-time constants. Shared Readonly
will still prevent anyone from changing the value.
Java doesn't actually have a concept like Const
- it just spots when static final
values are actually compile-time constants.
What you are looking for is the readonly keyword. A time stamp has to be calculated at run time and cannot be constant.
ReadOnly TIME_STAMP As String = Format(Now(), "hhmm")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With