Question

I've tried to create a vb scripts class with a constant and got 800A03EA error. It's it a VBS bug? Isn't it an OOP fundamental rule?

Class customer
   ' comment it const and its works
   const MAX_LEN=70

   Private Name

   Private Sub Class_Initialize
      Name = ""
   End Sub

   ' name property.
   Public Property Get getName
      getName = Name
   End Property

   Public Property Let letName(p_name)
      Name = p_name
   End Property
end class
Was it helpful?

Solution

The documentation lists all statements that are allowed in the context of classes. Const isn't among them, so it's not supported. You can work around the issue by using private member variables that you initialize during instantiation (i.e. in Class_Initialize):

Class customer
  Private MAX_LEN
  Private Name

  Private Sub Class_Initialize
    MAX_LEN = 70
    Name = ""
  End Sub

  ...
End Class

If instances of the class should expose this value, you could implement it as a read-only property:

Class customer
  Private MAX_LEN

  Private Sub Class_Initialize
    MAX_LEN = 70
  End Sub

  'read-only property, so no "Property Let/Set"
  Public Property Get MaxLength
    MaxLength = MAX_LEN
  End Property

  ...
End Class

However, as Ekkehard.Horner pointed out correctly, the value could still be changed by object-internal code. If immutability is the primary requirment for this value you should implement it as a global constant.

OTHER TIPS

I agree with Ansgar Wiechers's answer, but would like to propose another option.

If immutability is more important than performance, you could put the value directly in the Get and use the property to refer to the value instead of a class-level variable.

Class customer

  'read-only property, so no "Property Let/Set"
  Public Property Get MaxLength
    MaxLength = 70
  End Property

  ...
End Class

A Private variable (perhaps with a getter) gives you a value that is read-only from the outside of the class, but class internal code can still change that value.

So using a global Const (perhaps with a 'namespace' name part) may be a better workaround in cases where the constness is most important.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top