I have this code:
Public Class Beryllium
Public Const AtomicNumber As Byte = 4
Public Const Symbol As String = "Be"
Public Const Name As String = "Beryllium"
Public Const AtomicMass As Double = 9.012182
Public Const List = AtomicNumber & vbNewLine & Symbol & vbNewLine & Name & vbNewLine & AtomicMass 'This line
End Class
I want to make a list out of all the constants (AtomicNumber, Symbol, Name and AtomicMass). I want to make the list also a constant. When I run the code above, I get an error highlighting AtomicNumber (on line on which I commented on “This line”). I tried .ToString() and CStr() but I get errors on both. Maybe there is a different way to make these constants one string or list (must be public and have new lines)? Any ideas? Thanks.
You can’t do this in a constant expression because a constant expression requires the value to be computed during compile time. However, the “ToString()” value of a double is not known at compile time, because ToString is a method run by the Double class during runtime. So, the compiler has no idea what it will end up returning. However, .NET has the
readonlymodifier to deal with cases like this. If you change your line to:You’ll see it will work. This readonly field is computed as soon as the class is loaded into memory, and cannot be changed by any client, so it is almost equivalent to a const. The only difference being of course, you have some overhead of computing the value. Additionally, with consts, the compiler can perform some other optimizations, like literally substituting the constant value instead of dereferencing it. I.e., if your code says:
If you look at the compiled code, it will actually say: