Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a dynamic constant in VB .NET?

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?

like image 766
froadie Avatar asked Jan 27 '10 21:01

froadie


People also ask

Does VB 10.0 support keyword dynamic?

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.

How can a datatype be declared to be a constant type?

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.

Can we change constant variable C#?

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.

Which keyword is used to declare the variable in VB?

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.


2 Answers

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.

like image 126
Jon Skeet Avatar answered Jan 01 '23 09:01

Jon Skeet


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")
like image 29
ChaosPandion Avatar answered Jan 01 '23 08:01

ChaosPandion