Permanent Inner Class

I tried to create a vb script class with constant and got error 800A03EA. Is this a VBS error? Isn't that the basic rule of OOP?

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 
+6
source share
3 answers

The documentation lists all statements allowed in the context of classes. Const not among them, so it is not supported. You can work around the problem by using the private member variables that you initialize when you instantiate (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 class instances should expose this value, you can 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 pointed out by Ekkehard.Horner , the value can still be changed by the internal internal code. If immutability is a basic requirement for this value, you should implement it as a global constant.

+11
source

I agree with Ansgar Wiechers , but would like to suggest another option.

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

 Class customer 'read-only property, so no "Property Let/Set" Public Property Get MaxLength MaxLength = 70 End Property ... End Class 
+5
source

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

Thus, using the global Const (possibly with a part of the namespace name part) may be the best way to work around where a constant is important.

+4
source

All Articles