Charles Okwuagwu
Charles Okwuagwu

Reputation: 10866

Define a CONST string of characters "00000....." where the length is defined by another CONSTANT

    Private Const TOKEN_LENGTH As Integer = 8 ' this may come from app.config at startup
    Private Const TOKEN_MIN As Integer = 10 ^ (TOKEN_LENGTH - 1)
    Private Const TOKEN_MAX As Integer = 10 ^ TOKEN_LENGTH - 1

    'how do I make TOKEN_FORMAT a CONST?
    Private Const TOKEN_FORMAT As String = "0".PadRight(TOKEN_LENGTH)

    'sample usage
    Dim TokenCode As String = New Random().Next(TOKEN_MIN, TOKEN_MAX).ToString(TOKEN_FORMAT)

The following code gives this error: Constant expression is required.

Private Const TOKEN_FORMAT As String = "0".PadRight(TOKEN_LENGTH)

Once defined, TOKEN_FORMAT will never change, its definition simply depends on another constant TOKEN_LENGTH. so why cant it also be compile-time evaluated?

Upvotes: 0

Views: 66

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

You're trying to get too fancy. These are constants so give them constant values. Your TOKEN_LENGTH constant is pointless.

Const TOKEN_FORMAT As String = "00000000"
Const TOKEN_MIN As Integer = 10000000
Const TOKEN_MAX As Integer = 99999999

That's all you need.

Upvotes: 1

har07
har07

Reputation: 89285

Better in what way you needed? How about property without setter, for example :

Public Class ConstantTest
    Private Const TOKEN_LENGTH As Integer = 6
    Private ReadOnly Property TOKEN_FORMAT() As String
        Get
            Return "0".PadRight(TOKEN_LENGTH, "0"c)
        End Get
    End Property
    Private ReadOnly ANOTHER_TOKEN_FORMAT As String = "0".PadRight(TOKEN_LENGTH, "0"c)

    Public Sub New()
        'you can change readonly field in constructor...'
        ANOTHER_TOKEN_FORMAT = "test"
        'but setting "get-only" property is not allowed even in constructor'
        TOKEN_FORMAT = "test"   '<- compile error here'
    End Sub
End Class

You can change value of readonly field in constructor which make it less similar to Const, but the same trick can't be applied to a property without setter as demonstrated in above example.

Related discussions : const vs. readonly, What is the difference between const and readonly?

Upvotes: 0

Related Questions