views:

274

answers:

3

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?

+1  A: 

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")
ChaosPandion
+4  A: 

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.

Jon Skeet
+1  A: 

By definition, constants are not dynamic. If you want a variable to be set once, and not modified again, I believe you are looking for the ReadOnly keyword...

Public (Shared) ReadOnly TIME_STAMP = Format(Now(), "hhmm")
Josh Stodola